willFocus event in react navigation 5 - react-native

I need to fetch data before focus event. I saw that there was an willFocus event in react navigation 4 but it seems that the event was removed in react navigation 5.
componentDidMount cannot do the trick because I want to fetch data as soon as possible even before the screen comes into focus each time the user navigate to my screen.

You could do something like:
/**
* Your redux action should set loading-state to false after
* fetch-operation is done...
*/
reduxActionDoingFetch();
useEffect(() => {
if (reduxActionDoingFetch_Loading === false) {
Navigation.navigate('YourTargetScreen');
}
}, [reduxActionDoingFetch_Loading]);

You CANNOT fetch data before componentDidMount. That's literally the first thing happens when a new screen is rendered.
Regarding fetching data each time when the screen is focused, you need to use focus event as mentioned in the migration guide: https://reactnavigation.org/docs/upgrading-from-4.x/#navigation-events
The focus event equivalent to willFocus from before. It fires as soon as the screen is focused, before the animation finishes. I'm not sure what you mean by it fires too late.
Also, for data fetching, there is a special hook: useFocusEffect
https://reactnavigation.org/docs/use-focus-effect/

React.useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// do something
});
return unsubscribe;
}, [navigation]);

Related

Trigger UseEffect whenever i switch tabs in React Native Tab Navigator

I have implemented react native tab navigator and added 4 screens to it.
I post some record to api in the second screen and i want to have the updated record in the 4th screens where i am getting updated records..
Useeffect only gets targeted only once, and when i put something in it's argument it gives me strange behavior.
I want useeffect to reload and call the api to get latest items in the 4th screen without putting anything in it's arguement(empty argument)
Any help would be highly appreciated.
Try doing this ;
useEffect(() => {
const unsubscribe = navigation.addListener("focus", () => {
makeApiCall();
});
return unsubscribe;
}, [navigation]);
Get navigation in component's arguments(destructuring)
like below;
const My4thTab = ({ navigation }) => {
}
This way useEffect will trigger only once, every time you come on this screen
but make sure to clear the previous state where you store your data, otherwise, there could be a record duplication.
Hope it helps :)

Render useEffect/Async function from a difference screen

I have an async function and a useEffect that fetches data once.
const [data, setData] = useState([]);
async function fetchData() {
fetch(`${baseURL}api/v1/data/${userId}`)
.then((response) => response.json())
.then((response) => {
try {
if (response.length > 0) {
setData(response);
} else {
setData([]);
// console.log(response);
}
} catch (err) {
console.log('no response');
alert(err);
}
});
}
useEffect(() => {
fetchData();
}, [userId, data]);
I could remove the array on the use effect but it will always run the function if I do that.
So when I open the screen, it will fetch the latest data. However, if I want to add a new data from a different screen, it wont trigger the async nor the useEffect function. How should I tell RN that there is a new data? Would AsyncStorage work? to update a data from one screen and apply the data here? I am open for suggestions on how to proceed.
What I meant by a different screen: A register screen and a view screen. In this case, I already opened the View Screen before I open the register screen so view screen is already rendered.
In React Navigation and most of the navigation libraries, screens don't get unmounted from the stack when it's navigated to another screen. For example if you have a list of something and then you press to "+" button to navigate to the "new item" screen to add a new one, when you press back button, since the previous "list" screen was not unmounted from the stack, useEffect won't be triggered, and you won't get the new data.
There are a couple of solutions for this case:
You can hold your data in a global state, and when you update an item from another screen, after a successful API call, you can also update the global state. You can look for React Context, MobX or Redux for this.
You can pass parent's state with a callback from one screen to another if they are not that apart from each other. So that in the "new data" screen, you can call that callback function to change the parent screen's state too.
Third, and IMO the best way is using a hook called useFocusEffect by React Navigation itself: https://reactnavigation.org/docs/use-focus-effect
I hope these will help.

Expo React Native execute function when entering view

I'm trying to make a function execute when a view is in foreground, but just once not on each update of the component. If the user navigates to another view and goes back to the first view it should execute that function again, but just once. Is there a solution to this?
if using useEffect without second parameter it executes on each update, if I add [] as second parameter it only executes the first time the view is rendered but not when navigating back to it.
Any help appreciated!
if you are using react-navigation you can do this by listen on screen focus see here
React.useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// The screen is focused
// Call any action
});
// Return the function to unsubscribe from the event so it gets removed on unmount
return unsubscribe;
}, [navigation]);

react native while come back to previous screen the page data is not updated

I did some changes in my second screen and comeback to my first screen the data is not updated. After reloading app the data is updated. How to update the data from second screen to first screen navigation without refresh or reload
What i believe without any code is that if you do navigation.goBack() or navigation.navigate() it doesnt call the api if its in your componentDidMount, what you can try is adding an eventlistener called onFocus so that whenever screen is focused you call that :
like this in your componentDidMount
componentDidMount(){
this.focusListener = this.props.navigation.addListener('didFocus', () => {
// The screen is focused
// Calling action to reset current day index to 1
this.getItineryData();
});
}
Hope it helps

React-Native Tab Navigator memory leak due to no component willunmount

I am really confused how to solve the issue of canceling an async process when moving to a new tab. If you start an async request on a page but, then navigate to a new tab before it's complete, you will get the warning: "Can't call setState (or forceUpdate) on an unmounted component"
However, changing screens via the tab navigator will never fire the willunmount so, there is no real place to cancel any operations.
Stack Navigator and switch navigator fire this and I can cancel any operations just fine. I literally am about to build my own bottom nav to get around this.
This sample is way to hacky IMHO:
YES, I've tried the this.isMounted approach (BTW you now will get the isMounted(...) is deprecated warning if you use that) Yes, I've used the willupdate method but, PureComponent is suppose to remove that "hack".
This really feels like a bug to me and I am at lost to how to have a bottom Navigation AND have a page with some fetch results.
// Hacky Example in async method
try {
let response = await fetch(
'https://your/rest/endpoint/with/json'
);
if (response.ok) {
if (!_isMounted) {
console.log('oops! ' + SCREEN_NAME + ' was unmounted before async');
return; // just bail if component is no longer mounted
}
let responseJson = await response.json();
`
If you're using Redux:
You could move all of your Async Code into an Action ...
If you're executing your async code in an action instead of executing it inside your component's life ... it's ok if the user decided to move to a different tab and the action has not been resolved yet ((because it's running in a different context than the component's lifecycle)) ... once the action is done and your component is still active >> then it'll receive a new set of props to update itself ...
And regarding setting state on an unmounted component ... you could use this template for any class-based component that has a state:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
// other fields...
isUnmounted: false,
};
}
componentWillUnmount() {
this.setState({ isUnmounted: true });
}
setComponentState = (values) => {
if (!this.state.isUnmounted) this.setState(values);
};
}
Redux is not wrong but, for my case more complicated than required.
So, if anyone is struggling with React-Navigation Tab Navigator and async fetch. I was able to achieve the pattern I was after (firing an event to be able to cancel async events).
You CAN add a Listener when the screen is navigated to or from (blur)
React Navigation emits events to screen components that subscribe to them:
willFocus - the screen will focus
didFocus - the screen focused (if there was a transition, the transition completed)
willBlur - the screen will be unfocused
didBlur - the screen unfocused (if there was a transition, the transition completed)
basically I did this:
async componentDidMount() {
console.log(SCREEN_NAME + ' Component Did Mount');
this.props.navigation.addListener('willBlur', (route) => {
_isMounted = false;
this.axiosCancelSource.cancel('Component unmounted.');
});
// didFocus will fire on 1st Mount as well
this.props.navigation.addListener('didFocus', async (route) => {
_isMounted = true;
this.axiosCancelSource = axios.CancelToken.source();
await this._getTourList();
});
console.log(SCREEN_NAME + ' Component Did Mount Complete');
}
React-Navtive Navigation props web site