Customize fetchBasequery for error handling

Viewed 964

I'm using rtk fetchBase in my react app. From documentation I understood that we can create custom baseQuery to handle response. I want to write a baseQuery to handle 401 errors by dispatching a reducer in 401 handler.How do I create the custom baseQuery.

2 Answers

You can consider the following example:

export const baseQueryWithReauth: BaseQueryFn<
      string | FetchArgs,
      unknown,
      FetchBaseQueryError
    > = async (args, api, extraOptions = {}) => {
      const result = await baseQuery(args, api, extraOptions);
      if (result?.error?.status === RESPONSE_CODE.NO_AUTH) { // 401
        logout(); // Optionally you can trigger some code directly here
        // or dispatch an action to be handled in reducer or your middleware
        api.dispatch("whatever action you need");
      }
      return result;
    };

But from your question, it's not really clear what are you going to dispatch here. It's not a valid statement to "dispatch reducer". You can dispatch nothing but actions.

Error and success message handling inside of the baseQuery, you'd need to implement your custom errorToast and infoToast. Alternatively check out this link on the official docs.

const baseQueryToasts = (baseUrl) => {
  const baseQuery = fetchBaseQuery({ baseUrl });
  return async (args, api, extraOptions) => {
    const { error, data } = await baseQuery(args, api, extraOptions);
    if (error) {
      errorToast(error.data?.message || error.status || "unknown error");
      return { error: { status: error.status, data: error.data } };
    }
    if (data?.message) {
      infoToast(data.message);
      delete data.message;
    }
    return { data };
  };
};

export const sampleApi = createApi({
  reducerPath: "sampleApi",
  baseQuery: baseQueryToasts("/api/more/"),
  /* ... */
})
Related