Search code examples
javascriptreactjsredux-toolkithttp-status-code-401rtk-query

Override the maxRetries for only unauthorized error in RTK query


I have written base query like this and have added maxRetries count as 3.

export const baseQuery = retry(fetchBaseQuery({
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
    'Access-Control-Allow-Origin': '*'
  },
  prepareHeaders: (headers) => {
    if (!headers.has('Accept-Language') && accessToken) {
      headers.set('Accept-Language', i18n.language || 'en');
    }
    return headers;
  },
}), { maxRetries: 3 });

I don't need to retry on unauthorized errors. When I get 401 status I need to stop retrying. How can I do that?

I thought to do this using a RTK middleware, but only middleware is triggered after all retries. So is there any way to stop retrying only when I get a HTTP status 401 error?


Solution

  • You can bail out of retries. Create a custom base query function that checks the fetchBaseQuery result status and preemptively fails the retry logic.

    Example:

    export const baseQuery = retry(
      async (args, api, extraOptions) => {
        const result = await fetchBaseQuery({
          timeout: 5000,
          headers: {
            'Content-Type': 'application/json;charset=utf-8',
            'Access-Control-Allow-Origin': '*'
          },
          prepareHeaders: (headers) => {
            if (!headers.has('Accept-Language') && accessToken) {
              headers.set('Accept-Language', i18n.language || 'en');
            }
            return headers;
          },
        })(args, api, extraOptions);
    
        if (result.error?.status === 401) {
          retry.fail(result.error);
        }
    
        return result;
      },
      { maxRetries: 3 },
    );