Search code examples
reactjsrtk-query

Allow RTK-Query to retain the data for specific time period while refetching the data in the background


I'm new to React and in my project I'm using RTK-Query to retain the data after fetching it for some time. Everything is working well, but I can't seem to wrap my mind around the caching strategy. To put it simply, I want it to behave in such a way that when the hook is called after 5mins, it will return the old data first + refetching the data in the background, then re-render the component with the new data, so no loading state to be shown to the user. From what I understand, with my current configuration, it will return undefined (aka no data) 5m after last access, and refetch the data 5m after last fetch. How can I achieve this? I'm thinking of increasing the retention time to longer time, but the policy only allows 5mins so I'm a bit stuck here.

Here is my code (I omitted some parts to make it easier to understand)

const api = createApi({
  reducerPath: 'api',
  baseQuery: fakeBaseQuery(),
  endpoints: (builder) => ({
    getApi: builder.query({
      queryFn: async () => {
        ...
      },
      // keep the data for 5 mins after last usage
      keepUnusedDataFor: 60 * 5,
    }),
  }),
  // allow refetch the data after 5 mins from last fetch in background
  refetchOnMountOrArgChange: 60 * 5,
});

Thank you for the help


Solution

  • refetchOnMountOrArgChange will do what you want, but as long as you have keepUnusedDataFor set to the same value, old data will get thrown away so you always start with undefined. Set that to a higher value or remove the option.