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

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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, {}>.

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x