1. 18
    Refetch Data on Focus And Reconnect with RTK Query's setupListeners
    1m 6s

Refetch Data on Focus And Reconnect with RTK Query's setupListeners

Jamund Ferguson
InstructorJamund Ferguson
Share this video with your friends

Social Share Links

Send Tweet

This is a small lesson that covers a tiny feature of RTK Query that enables two additional refetch options: refetchOnMount and refetchOnReconnect.

In order to support them you need to include setupListeners() in your redux store. And then you'll have the ability to automatically refetch data when your page comes into focus or reconnects to the network. The main idea is if you're outside of the page on a different app and come back it will make sure your users are seeing the most up-to-date information.

More information about these options can be found here:

  • https://redux-toolkit.js.org/rtk-query/overview#configure-the-store
  • https://redux-toolkit.js.org/rtk-query/api/createApi#refetchonfocus
  • https://redux-toolkit.js.org/rtk-query/api/createApi#refetchonreconnect

Instuctor: [0:00] Inside of store/index.js, import setupListeners from reduxjs/toolkit/query. Then at the bottom of the file, type setupListeners(store.dispatch). Now in your apiSlice, go ahead and add two lines -- refetchOnFocus true and refetchOnReconnect true.

[0:21] Now when you change tabs and come back to the web page, the data will be refetched automatically. Whether or not you're going to need this feature really depends on your app and your use case, but let's see what it looks like.

[0:33] On the website here, I'm going to open up my web inspector, go to the network tab, filter by api and fetch, and go onto the Services page. You see it loads the service and dogs apis. Now, I'm going to change tabs, come back. It decided to fetch both of those calls automatically.

[0:49] That's what refetch on focus does when you essentially leave the window at all and come back, it will refetch automatically for you. Then refetch on reconnect will automatically repull data after your connection drops and reestablishes. This is probably more likely useful in mobile scenarios.