Re-Execute a Query with Pull To Refresh in React Native

Kadi Kraman
InstructorKadi Kraman

Share this video with your friends

Send Tweet
Published 2 years ago
Updated 2 years ago

Now we'll implement pull-to-refresh and refetch the data on Stories and Bookmarks. To do this, we'll create React component state in the HomeScreen to track whether the component is refreshing or not.

We'll set the FlatList with refreshing and onRefresh properties to allow for the native refresh behavior you would expect from an app.


  • Re-executing queries:

Checkpoint: Add pull to refresh

Instructor: [0:00] The useQuery hook returns an array of two items. The first item is information about the query, so the data, error state, and fetching state. The second item is a function that allows you to re-execute the query. We'll call it Refresh Stories.

[0:13] Urql won't be able to distinguish between the fetching state and refreshing state so we'll need a separate state variable. We'll do const isRefreshing and set isRefreshing. This will be a React useState with the initial value of false. We'll need a const handle Refresh Stories.

[0:29] This will be a React useCallback, and set isRefreshing to true and call Refresh Stories. We can pass in an object with request policy of network only. Let's also update the dependencies array.

[0:40] The default request policy for queries is network only being that if the data already exists in the cache, the network request gets emitted, and the cache value gets returned instead.

[0:49] In order to force this Refresh Stories to actually execute a network request, we'll need to set the request policy to be network only. Next, to ensure that this isRefreshing gets set back false, we'll need a React useEffect. This will check if the fetching state is false. If not fetching, set isRefreshing to false. I'll need to add fetching to the dependencies array.

[1:08] Currently, we're going to return a full screen loading page whenever fetching is true, but we don't want to return this if we are just re-fetching. Here in if statement, let's only return this if we're fetching and if we are not refreshing. Last, let's scroll down to the flat list.

[1:23] Let's do refreshing = isRefreshing, and onRefresh = handle Refresh Stories. Now when we reload the app, we'll can use pull-to-refresh to update the stories. Let's open a bookmark screen and also de-structure refresh bookmarks.

[1:37] We can copy the useStates, useCallback and useEffect from the home screen and paste it underneath a query. Here we'll need to update our variables. If we refresh bookmarks, instead of stories for our loading page, we need to do if fetching and if not isRefreshing.

[1:51] In the flat list, we'll do refreshing = isRefreshing, and onRefresh = handle refresh bookmarks. After we load our app and go to the bookmarks tab, we can use pull-to-refresh on the bookmarks.