DEV Community

Cover image for Refetching in React Native with 1 line of code
Rodrigo Figueroa
Rodrigo Figueroa

Posted on • Updated on • Originally published at Medium

Refetching in React Native with 1 line of code

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 mounted or 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 willFocus, didFocus, willBlur, and didBlur.

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())
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (2)

Collapse
 
gokcan profile image
Gokcan Degirmenci

Nice but don't forget to call removeListener() on componentWillUnmount() of an appropriate component.

Collapse
 
constantince profile image
constantince

Nice solution. Navigation.goback() or browser back button doesn't trigger the lifecycle method, but the event will.