Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 290
Obaid Aqeel Avatar asked Dec 03 '25 12:12

Obaid Aqeel


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.
}
like image 77
phry Avatar answered Dec 05 '25 09:12

phry


I found the answer for your question here written by Phry as well :) ,

https://github.com/rtk-incubator/rtk-query/issues/86#issuecomment-738845312

If you know the format that will be returned with all non-2xx-status responses from your server, you could just cast your

fetchQuery as BaseQueryFn<string | FetchArgs, unknown, YourErrorType, {}>.

enter image description here

like image 22
Mohammed Said Elattar Avatar answered Dec 05 '25 09:12

Mohammed Said Elattar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!