reduxjs / redux-toolkit

The official, opinionated, batteries-included toolset for efficient Redux development
https://redux-toolkit.js.org
MIT License
10.68k stars 1.16k forks source link

Change headers on cache invalidation #4487

Open pkolt opened 3 months ago

pkolt commented 3 months ago

Hi, guys! 🖐️

I have question about RTK Query.

I use providesTags for Invalidating cache data. It happen after mutate operations.

How do I change headers for queries that do cache invalidation? I can't distinguish queries that do cache invalidation from other queries.

prepareHeaders(headers, api) {
    // In this point I want to add header if query for cache invalidation
    headers.set('X-Worker-Clear-Cache', 'true');
    return headers;
}
zarqani commented 3 months ago

You can add a custom flag to your endpoints that should have a special header. For example, you can add a clearCache property to the endpoints that invalidate the cache.

const api = createApi({
  baseQuery: fetchBaseQuery({
    baseUrl: '/api',
    prepareHeaders(headers, { endpoint }) {
      // Check if the endpoint has a custom property 'clearCache'
      if (api.endpoints[endpoint]?.clearCache) {
        headers.set('X-Worker-Clear-Cache', 'true');
      }
      return headers;
    },
  }),
  endpoints: (builder) => ({
    getItems: builder.query({
      query: () => '/items',
      providesTags: ['Items'],
      // Add the custom flag to this endpoint
      clearCache: true,
    }),
    addItem: builder.mutation({
      query: (newItem) => ({
        url: '/items',
        method: 'POST',
        body: newItem,
      }),
      invalidatesTags: ['Items'],
      // Add the custom flag to this endpoint
      clearCache: true,
    }),
  }),
});

export const { useGetItemsQuery, useAddItemMutation } = api;