How to properly type data in useMutation?
Hello everyone! I am using Tanstack React Query v4.36.1. Please help me to type this correctly? I don't understand why it's not working!
I'm using type AxiosResponse<User> and I can see that the correct data is being returned. But it still results in the following error:
Here is my code:
7 Replies
quickest-silver•12mo ago
You shouldn't have to add a generic to useMutation. It will infer from the return type of the mutationFn. This is recommended so you don't miss things like undefined.
Although your type error is on the key so are you sure this is the exact code that threw this error? Mutation types work fine for me without the generic.


ratty-blushOP•12mo ago
Thank you for your answer!
Actually, I just want to type the error, but I can only do that without typing the data from the server.
This issue occurs consistently in all components.
I even tried writing useMutation<any, AxiosError>(), but that doesn't help either, TypeScript still complains.
useful-bronze•12mo ago
https://tanstack.com/query/latest/docs/framework/react/typescript#typing-the-error-field
You can probably just register it globally like here: https://tanstack.com/query/latest/docs/framework/react/typescript#registering-a-global-error
TanStack | High Quality Open-Source Software for Web Developers
Headless, type-safe, powerful utilities for complex workflows like Data Management, Data Visualization, Charts, Tables, and UI Components.

useful-bronze•12mo ago
Just realized you said v4 so I guess ignore the global solution. That's v5
automatic-azure•12mo ago
TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
automatic-azure•12mo ago
Actually, I just want to type the erroryou can't. It's not guaranteed that the only errors that happen in your mutation are
AxiosError
. For example, if you do something wrong in onMutate
, you might get a runtime error that isn't of type AxiosError
. I would just use the isAxiosError
function at runtime that also narrowsautomatic-azure•12mo ago
TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.