skip to Main Content

Currently, i implement custom hook for useMuatation hook for separation of concern and reusable. Typescript is complaining my createBook function ***Type ‘(bookData: Shop) => Promise’ has no properties in common with type ‘UseMutationOptions<Shop, Error, Shop, unknown>’ ***. Here is 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 type for that error. I am currently using react query v5.28.14.

2

Answers


  1. The error is pretty clear

     return useMutation<Shop, Error, Shop, unknown>({
        mutationFn: createBook,
        onSuccess: () => {
          // invalidate the query cache for 'shop'
        },
      });
    
    Login or Signup to reply.
  2. You need to ensure that your createBook function conforms to the UseMutationOptions type. Specifically, it should return a promise with the same type as the first type parameter, Shop, and handle potential errors.

    Try updating your createBook function to explicitly define its return type as a promise with the correct type:

    const createBook = async (bookData: Shop): Promise<Shop> => {
      const { data } = await apiClient.post("/books", bookData);
      return data;
    };
    

    By specifying the return type as Promise<Shop>, you are ensuring that it matches the expected type for the useMutation hook. This should resolve the type error you’re encountering.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search