Obaid Aqeel
Obaid Aqeel

Reputation: 391

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

Upvotes: 19

Views: 21017

Answers (4)

Sandeep Vaid
Sandeep Vaid

Reputation: 1

I have following type of error message coming from backend

{
  "status": 400,
  "data": {
    "success": false,
    "message": "Course already enrolled"
  }
}

and to get the message we can use the following form of code snippet

if(enrollCourseToLearnerError && 'data' in enrollCourseToLearnerError){
        const notification :INotification = {
            title:"Error in enrolling course",
            message:(enrollCourseToLearnerError.data as { message: string })?.message,
            position:"top-right",
            color:"red"
          }

        notifications.show(notification);
        }     

We are just checking whether the required keys are there so that typescript give no error .

Upvotes: 0

Ahmed
Ahmed

Reputation: 945

I ended up working around it in the component itself In my case I needed the error to be of type Record<string, string>

// In the component arrow function where I use the RTK Query hook
const [register, { error }] = useRegisterMutation();
const errors = (): Record<string, string> => {
    if (error && (error as Record<string, string>)) {
      return error as Record<string, string>;
    } else {
      return {};
    }
  };

// In the rest of the code, I can just call
errors().propertyName // and check if it is undefined where I need to

I don't believe this is ideal, but did not figure out better work around so far

Upvotes: 1

Mohammed Said Elattar
Mohammed Said Elattar

Reputation: 377

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

Upvotes: 8

phry
phry

Reputation: 44226

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

Upvotes: 26

Related Questions