reactjstypescriptreduxrtk-query

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


I'm 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"
    }
}

I'm 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'.


Solution

  • 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.
    }