How to stop Redux RTK query from retrying on error

Viewed 1462

I have some requests which may return 404s. When they do, RTK query will send retries, resulting in hundreds of failed requests. Why is it trying to refetch on error and what can I do?

3 Answers

If your endpoint is in error, RTK Query's useQuery will send a request in two situations:

  • you change the argument (that would always result in a new request)
  • you mount a component using this useQuery.

So without seeing your code, I would assume that your component re-mounts somehow and thus leads to another request after mounting.

As docs say, for custom error handling we can use queryFn:

One-off queries that use different error handling behaviour

So if, for any reason, you want to cache request on error, you can do:

getPokemon: build.query<Pokemon, string>({
  async queryFn(name, api, extraOptions, baseQuery) {
    const result = await baseQuery({
      url: `https://pokeapi.co/api/v2/pokemon/${name}`,
      method: 'GET'
    });

    if (result.error?.status === 404) {
      // don't refetch on 404
      return { data: result.data as Pokemon };
    }

    if (result.error) {
      // but refetch on another error
      return { error: result.error };
    }

    return { data: result.data as Pokemon };
  }
}),

you can limit the number of retries that rtk automatically does by using the property maxRetries inside your end point.

import { createApi, fetchBaseQuery, retry } from 
'@reduxjs/toolkit/query/react'

// maxRetries: 5 is the default, and can be omitted. Shown for 
documentation purposes.
const staggeredBaseQuery = retry(fetchBaseQuery({ baseUrl: '/' }), {
  maxRetries: 5,
})
export const api = createApi({
  baseQuery: staggeredBaseQuery,
  endpoints: (build) => ({
    getPosts: build.query({
      query: () => ({ url: 'posts' }),
    }),
    getPost: build.query({
      query: (id) => ({ url: `post/${id}` }),
     extraOptions: { maxRetries: 5 }, // You can override the retry behavior on each endpoint
    }),
  }),
})

export const { useGetPostsQuery, useGetPostQuery } = api
Related