React Redux: How to handle errors in RTK Queries/Mutation Typescript?

Viewed 3739

Hope your all are doing fine.

Im using Typescript with RTK mutation everything is working good but if i send any error from backend in specific json format like

{ 
   status: "Error",
   message "Something went wrong"
}

when i check on my browser network tab its showing me the correct error response like:

{
   data: { 
      status: "Error",
      message "Something went wrong"
    }
}

Im getting error in the mutation hook:

const [createCategory, {isLoading, error }] = useCreateCategoryMutation();

but I can't access error.data.message in my react it is giving me types error like:

Property 'data' does not exist on type 'FetchBaseQueryError | SerializedError'.
2 Answers

At this point, it could be an error from the server (FetchBaseQueryError) or just any error thrown by code you wrote (SerializedError, e.g. in query, queryFn, transformResponse etc.) - and that could have a completely different shape.

To make sure it's a FetchBaseQueryError, just do

if ('data' in error) {
  // TypeScript will handle it as `FetchBaseQueryError` from now on.
}
Related