Coming from a Vue.js background I have experienced components that unmont every time you navigate to another route/component. So as you can see using lifecycle methods like
created was a common pattern to rerun logic if needed. You may need this e.g. in a news feed if you get back to the feed from a feed item screen and you need to show the newest feed from your API.
So back to React Native I found myself in this new scenario where components do not mount/unmount from screen to screen. So what to do? Turns out that the solution was in the navigation.
I am using React Navigation which enables you to emits events to screen components that subscribe to them. With that functionality you can use the event that best suit you. You get
In my particular use case I needed to refetch when coming back from the previous screen. When the user pressed that back button I needed to reflect the changes so I used
willFocus to fetch right away, before the render started.
I thought of using
willBlur on the feed item screen before returning to the main feed saving the fetch response on store but
willFocus worked just fine.
Going to the point, to solve refetch that one liner you need is:
this.props.navigation.addListener( "willFocus", e => this.fetch())
You can call this listener on a new property of your class or in a lifecycle method.
How you fetch as always is up to you but with React Navigation and listeners your refetching is plain and simple.
There are other use cases where solutions like Relay’s
QueryRenderer will be what you need. This could involve more complex scenarios such as needing foreground/background fetching, but for now and for me this was all I needed. Hope it helps you too. Happy refetching.