Search code examples
reactjsreduxredux-toolkit

Caching with redux-toolkit's createApi


I am caching product data coming from /products/name API using the Products tag and I want to re-fetch only when the product list has been updated. But I am concerned that I could still get cached data if someone else (another user) has updated the products and I didn't call /add-product API.

Then what's the use case of caching data using tags in using createApi?

    ...
    endpoints: (builder) => ({
      getProducts: builder.query({
        query: () => `/products`,
        provideTags: 'Products',
      }),
      addProduct: builder.mutation({
        query: ({ product }) => ({
          url: `/add-product`,
          method: 'put',
          body: product,
        }),
        invalidateTags: 'Products'
    }),
    ...

Solution

  • RTK Query's main purpose is to help keep data on the client in sync with what's on the server.

    As part of that, the philosophy of RTK is that it's best to re-fetch data from the server any time something may have changed, so that the client always has the most current data.

    "Tags" are used to manage relationships between mutations and queries. When you run a mutation, you're telling the server "go update this data". That means the data on the server is now newer than what's on the client, so we should re-fetch the related data and keep the client up to date. By attaching the same tag from a query's providesTags into a mutation in invalidatesTags, RTKQ knows that any time the mutation runs it should re-fetch the related queries.

    If you think there's cases when someone else other than this user may have updated the data on the server, you can also configure RTKQ to automatically poll and re-fetch the data on a timer.

    More details: