javascriptredux-toolkitrtk-query

How to handle error as success in RTK Query?


I have an endpoint that throws 404 when nothing is found.

However, in my app I want to treat those 404 of that endpoint as a 200.

transformErrorResponse: (error, meta) => {
  console.log('fetch error', error);
        
  return error;
},

Is there any way I can tell Redux-Toolkit that if the error is 404 then treat this as a 200 and potentially return an empty array?

How would I achieve this?


Solution

  • You can't change the error handling process from transformErrorResponse as by this point it's too late, an error has been returned from the base query already and this only allows you to transform the error, not change it back to a "success".

    What you can do, however, is create a custom base query function that checks the error status code and only returns errors for non-404 status code errors. See Customizing Queries for details.

    Example:

    import { fetchBaseQuery } from "@reduxjs/toolkit/query/react";
    
    const baseQuery = (baseQueryArgs) => 
      async (args, api, extraOptions) => {
        const result = await fetchBaseQuery(baseQueryArgs)(args, api, extraOptions);
    
        // Check is 404 error status and return valid data response
        if (result.error?.status === 404) {
          return {
            data: [],
          };
        }
    
        return result;
      };
    

    Usage:

    import { createApi } from '@reduxjs/toolkit/query';
    import { baseQuery } from '../path/to/baseQuery';
    
    export const myApi = createApi({
      baseQuery: baseQuery({
        baseUrl: "https://somedomain.com/api/",
        // ... other configuration properties ...
      }),
      endpoints: builder => {
        // ...
      },
      // ... other API slice properties
    });