I'd like to refresh the data on the screen in a react native app whenever the screen appears - like in a ViewWillAppear
method. I tried using the componentWillMount
method but it looks like it fires once before it appears, and doesn't fire again when the view is navigated to again.
Looking at this example https://reactnavigation.org/docs/guides/screen-tracking, it looks like I can add a listener on the onNavigationStateChange
method on the root navigation, but I'd like to keep the logic in the screen as it gets confusing if I move the data fetch logic for that one scree outside to the root navigator.
I've tried to follow the example and set that method to my stacknavigation but it doesn't seem to trigger.
<RootNavigation ref={nav => { this.navigator = nav; }}
onNavigationStateChange={(prevState, currentState, action) => {
// maybe here I can fire redux event or something to let screens
// know that they are getting focus - however it doesn't fire so
// I might be implementing this incorrectly
const currentScreen = getCurrentRouteName(currentState);
const prevScreen = getCurrentRouteName(prevState);
if (prevScreen !== currentScreen) {
console.log('navigating to this screen', currentScreen);
}
}}
/>
Here is my navigator reducer.
And then we have to connect the module/route to the redux store (sceneIsActive is the important bit):
And then inside your component, you can watch for/trigger code when the scene becomes active:
Know that
componentWillReceiveProps
does not run when initially mounted. So don't forget to call yourdoSomethingWhenScreenBecomesActive
there as well.You can use focus/blur event listeners(demonstrated here and discussed here).
So here's how I did it using the
onNavigateStateChange
.And in your screen you can check to see if your view will appear, note
MyPage
is the route name from your navigation object.