1

I am requesting the server in localhost for some information using RTK Query. But when the server is not running it showing FETCH_ERROR. I want to handle this error. i.e when this happen i want to show a toast notification. But I can't catch this error. So I need help to do that

Have look how the error looks like

1 Answers1

0

This could be a way to do that

const baseQuery = fetchBaseQuery({
  baseUrl: process.env.REACT_APP_API_URL,
  mode: "cors",
  prepareHeaders: (headers, { getState }) => {
    // Set your headers
    return headers;
  },
});

const baseQueryWithLogout: BaseQueryFn<
  string | FetchArgs,
  unknown,
  FetchBaseQueryError
> = async (args, api, extraOptions) => {
  let result = await baseQuery(args, api, extraOptions);
  if (result.error && result.error.status === "FETCH_ERROR") {
    // Handle your notification here
    return Promise.reject("Error");
  }
  return result;
};

If result.error.status is not exactly what you're looking for then you can play with the value that best suit your use case

  • That takes a "handled" error and makes it "unhandled", causing all kinds of problems within RTK Query. Never `return Promise.reject` within a `baseQuery`. `return { error: ... }` instead. – phry Mar 08 '23 at 07:15