Home > Back-end >  Trigger UseEffect whenever i switch tabs in React Native Tab Navigator
Trigger UseEffect whenever i switch tabs in React Native Tab Navigator

Time:11-23

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.

CodePudding user response:

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, everytime you come on this screen but make sure to clear previous state where you store your data, otherwise there could be a record duplication.

Hope it helps :)

  • Related