Dmitry Avgustis
Dmitry Avgustis

Reputation: 1131

How to invalidate RTK query caches(reset state) globally?

Project uses redux toolkit and rtk query. Data are fetched from one api, but the code is split into smaller chunks to reflect logical parts like

...etc

After logout rtk query preserves its state, so on next login the data are old. They might not even reflect the current user. How can I invalidate all the caches?

Upvotes: 30

Views: 59977

Answers (3)

Jamal Ashraf
Jamal Ashraf

Reputation: 935

SOLUTION: This will immediately remove all existing cache entries, and all queries will be considered 'uninitialized'. So just put the below code into onClick or according to your scenario so when you hit an enter request will go and cache would also be clear. Below here api is your name of an api which you would set in your rtk query in store.

dispatch(api.util.resetApiState());

For more info please have a look in documentation https://redux-toolkit.js.org/rtk-query/api/created-api/api-slice-utils

Upvotes: 24

Dmitry Avgustis
Dmitry Avgustis

Reputation: 1131

Actually it is pretty simple, but I had to refactor the code.

I created new api for each logical part. So to invalidate cache I would have to reset each api's state individually.

Fortunately rtk has code splitting capabilities in it: https://redux-toolkit.js.org/rtk-query/usage/code-splitting

Basically you create baseApi likes this:

export const baseApi = createApi({
  baseQuery: fetchBaseQuery({
    baseUrl: `${BASE_URL}/api`,
    prepareHeaders: (headers, { getState }) => {
      const token = (getState() as RootState).auth.token;
      if (token) {
        headers.set("authorization", `Bearer ${token}`);
      }
      return headers;
   },
  }),
  tagTypes: ["Vehicle", "CompanySetting", "Associate"],
  endpoints: () => ({}),
});

Then you can add api slice to it in a separate file, like so:

export const companySettingsApi = baseApi.injectEndpoints({
  endpoints: (builder) => ({
    getCompanySettings: builder.query<CompanySetting[], void>({
      query: () => ({
        url: `/companySettings`,
      }),
      providesTags: (_) => ["CompanySetting"],
    }),
    setCompanySettings: builder.mutation<void, CompanySetting[]>({
      query: (companySettings) => ({
        url: `/companySettings`,
        method: "PUT",
        body: companySettings,
      }),
      invalidatesTags: (_) => ["CompanySetting"],
    }),
  }),
});

This gives you ability to reset entire api state with a single dispatch

dispatch(baseApi.util.resetApiState());

Upvotes: 47

Kristjan
Kristjan

Reputation: 319

In case you need to reset only specific cache, for example CompanySettings, you can also use:

dispatch(api.util.invalidateTags(['CompanySettings'])

Documentation https://redux-toolkit.js.org/rtk-query/api/created-api/api-slice-utils#invalidatetags

Upvotes: 19

Related Questions