Sanjay Kapilesh
Sanjay Kapilesh

Reputation: 399

Redux Toolkit Query not invalidating tags and cache in non - debug or production mode

In my application when a user is logged in as a guest an authorization token is stored in Async Storage which is then used to fetch data from the API.

When the Guest logs into their account, The token is updated in Async Storage and is also updated in RTK Query

The API was created using createApi in Redux Toolkit

The base query of the createApi is

baseQuery: fetchBaseQuery({
    baseUrl: API_HOST,
    prepareHeaders: async headers => {
      const token = await AsyncStorage.getItem('token');
      console.log('Preparing Headers', token);
      if (token) {
        headers.set('authorization', `Token ${token}`);
      }
      return headers;
    },
    refetchOnMountOrArgChange: 30,
  }),

After the user signed in the headers of the RTK Query is changed to the updated token

Preparing Headers f770b8635dc3e5613a648fc****************

I use invalidateTags from createAPI to invalidate the cache data

dispatch(commonApi.util.invalidateTags(ALL_TAG_TYPES));

Here ALL_TAG_TYPES is an array of all tag types in the application

export const ALL_TAG_TYPES = [
  TAG_USER_AUTH,
  TAG_HOME_DATA,
  TAG_COURSE_DATA,
  TAG_BUNDLE_DATA,
  TAG_LIVE_CLASS_DATA,
  TAG_USER_ALL_DATA,
  TAG_USER_COURSE_DATA,
  TAG_USER_PROFILE_DATA,
  TAG_USER_WORKBOOK_DATA,
  TAG_PAYMENT_DATA,
  TAG_WORKSHOP_DATA,
]

The cache is invalidated in Debug Mode , Whereas fails to update in non - debug / production mode

React Redux version used is 7.2.5

Redux js toolkit version used is 1.6.1

The header of the query is changed whereas the cache data isn't invalidated

Upvotes: 0

Views: 1698

Answers (1)

Sanjay Kapilesh
Sanjay Kapilesh

Reputation: 399

The above error was because Redux doesn't deep check objects in Production mode to enable faster invalidation.

Since the schema of the JSON didn't change the cache was not invalidated in production

You need to pass serializableCheck and immutableCheck as true in your middleware to enable deep objects check in production in debug mode they are on by default

This might affect the speed of checks in production in case of large json objects. Hence they are disabled by default in production.

export const store = configureStore({
  reducer: {
    auth: authReducer,
    [commonApi.reducerPath]: commonApi.reducer,
  },
  middleware: getDefaultMiddleware =>
    getDefaultMiddleware({
      serializableCheck: true,
      immutableCheck: true,
    }).concat([
      commonApi.middleware,
      immutableInvariantMiddleware,
      rtkQueryErrorLogger,
    ]),
});

Redux Docs on Default Middleware - https://redux-toolkit.js.org/api/getDefaultMiddleware#included-default-middleware

Upvotes: 0

Related Questions