1

What is the type of error in react-query MutationCache onError function in Typescript. and how to override the type so that I can take the fullMessage from data, and use it

const queryClient = new QueryClient({
    mutationCache: new MutationCache({
        onError: (error) => {
          const serverError = error as IServerError;

          toastError(serverError?.response?.data?.fullMessage);
        },
    }),
});

I don't want to use the

const serverError = error as IServerError;

as it feels hacky.

I can see using webstorm that there are generics I can pass to it, but I don't understand how can I pass those generics to it.

2 Answers 2

2

error is of type unknown because react-query cannot know which kind of errors are produced by your query / mutation. You can throw 5 and then error would be of type number.

If you think you know it's of type IServerError, then you'd need to do a type assertion. The safe thing to do would be a runtime check with a user defined type guard.

To narrow for Error, all you need is:

if (error instanceof Error) {
  // error is now of type Error
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yes but what is Error here ? You mean if(serverError?.response?.data instanceof Error) But even so, would it remove the typescript complain?
Error is the build-in Error class. If you have a custom Error IServerError you'd need to write a user defined type guard (like axios does with isAxiosError), or use a type assertion.
0

checked this docs :)!

https://tanstack.com/query/latest/docs/framework/react/typescript#registering-a-global-error

import '@tanstack/react-query'

declare module '@tanstack/react-query' {
  interface Register {
    defaultError: AxiosError
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.