'Type error when using onMutate in react query (Optimistic Updates)
export const usePostApi = () =>
useMutation(['key'], (data: FormData) => api.postFilesImages({ requestBody: data }));
Query Definition
const { mutateAsync } = usePostApi();
const {data} = await mutateAsync(formData, {
onMutate: () => {},
});
component
After defining the query in one place, it is called and used in the component. When calling mutateAsync from a component, an option is provided as the second argument, but if onMutate is put, the following type error occurs. Any idea how to solve it?
error message: Argument of type '{ onMutate: () => void; }' is not assignable to parameter of type 'MutateOptions<ResponseData, unknown, FormData, unknown>'. Object literal may only specify known properties, and 'onMutate' does not exist in type 'MutateOptions<ResponseData, unknown, FormData, unknown>'.
Solution 1:[1]
onMutate only exists on the options that you pass to useMutation, not the ones that you pass to mutate. So if you want to use onMutate, you need:
export const usePostApi = () =>
useMutation(
['key'],
(data: FormData) => api.postFilesImages({ requestBody: data }),
{
onMutate: () => ...
}
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | TkDodo |
