Blog>
Snippets

Invalidating Tags to Refetch Related Data

Introduce a scenario where a user's data is updated and demonstrate how to invalidate related query tags to trigger refetching of the user list that now includes the updated information.
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

export const userApi = createApi({
  reducerPath: 'userApi',
  baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
  tagTypes: ['User'],
  endpoints: (builder) => ({
    getUsers: builder.query({
      query: () => '/users',
      providesTags: ['User'],
    }),
    updateUser: builder.mutation({
      query: ({ userId, ...patchData }) => ({
        url: `/users/${userId}`, 
        method: 'PATCH',
        body: patchData,
      }),
      invalidatesTags: ['User'],
    }),
  }),
});
Defines a user API with a 'getUsers' query and an 'updateUser' mutation. Upon successful update, the mutation will invalidate the 'User' tag, causing any active 'getUsers' subscriptions to refetch.