Type error in react query useMutation hook
Try to implement custom hook with useMuatation for POST request. Typescript is complaining that my createBook function Type '(bookData: Shop) => Promise' has no properties in common with type 'UseMutationOptions<Shop, Error, Shop, unknown>' . Here is an overview of my code.
useCustoumMatation.ts
import apiClient from "@/services/api/api-client";
import { useMutation } from "@tanstack/react-query";
type Shop =
{ shopCode: string;
shopName: string;
mobileNo: string;
address: string;
};
const createBook = async (bookData: Shop) => {
const { data } = await apiClient.post("/books", bookData);
return data;
};
export const useCreateBook = () => {
return useMutation<Shop, Error, Shop, unknown>(createBook,
{ onSuccess: () => {
// invalidate the query cache for 'shop' }, }); };
ShopList.ts
const {mutate} = useCustoumMatation() const onSubmit = (data:Shop) => {
mutate(data)
}
How can i properly pass the type for that error. I am currently using react query v5.28.14.
7 Replies
typical-coral•2y ago
You need to type the return type of
createBook
function. Your apiClient.post
method should support generic for the return type.
Check your data it should be of a Shop
type. And the return type of createBook
should be Promise<Shop>
typical-coral•2y ago
typical-coral•2y ago
useMutation now have slightly different API, you need to provide mutationFn like this
In most cases you don't need to provide types for your useMutation like this
<Shop, Error, Shop, unknown>
unless you want to type the Error. Let TS do its magic for you.optimistic-goldOP•2y ago
@denis.monastyrskyi Noted brother. By the way what if i want my mutation hook more generic for the same mutation logic in this case.
How can i pass that genric type. For current implementation it says Argument of type is not assignable to parameter of type 'void'
How can i pass that genric type. For current implementation it says Argument of type is not assignable to parameter of type 'void'
typical-coral•2y ago
I'm sorry, I didn't get it. What are you trying to pass and where?
optimistic-goldOP•2y ago
@denis.monastyrskyi I want to create shop more generic for the same mutation logic, eg. createCustomer, createStaff. I have to make "/shops" , formData in this case shopData and returned value from mutation fn statically. How can i properly pass the type when calling useCreateShop.
typical-coral•2y ago
Sorry, can't help You with that. Maybe @TkDodo 🔮 can help