reactjsreact-query

Uncaught runtime errors while using useMutation from react-query


I have a hook to upload statement of account, it was throwing error without a clear error

I had initially cleared some other hooks and rewrote the useStatement hook, however, it seems i am still getting something wrong.

I had the implementation like the below,

export const useUploadStatement = () => {
const { refetch } = useGetStageOneTransactions();

return useMutation(uploadStatement, {
    onSuccess: (data) => {
        console.log("Upload successful:", data.message);
        refetch();
    },
    onError: (error) => {
        handleError(error, "Error uploading. Please check your network and retry!!!");
    },
});
};

I thought the issue was because i was passing uploadStatement directly to the useMutation, i changed it to below, nothing changed.

import { useMutation, useQuery } from "@tanstack/react-query";
import Utils from "../shared/localStorage";
import toast from "react-hot-toast";
import { 
approveStageOne, 
approveStageTwo, 
getStageOneList, 
getStageTwoList, 
revertRecord, 
uploadStatement 
} from "../apis/reconciliation";

// Utility function to handle API errors
const handleError = (error, defaultMsg) => {
const message = error.response?.data?.msg || "An unexpected error occurred";
const errorMsg = error.response?.status === 500 ? defaultMsg : message;

toast.error(errorMsg, { position: "top-right" });
console.error(defaultMsg, error.response?.data?.error || message);
};

export const useUploadStatement = () => {
const { refetch } = useGetStageOneTransactions();

return useMutation((data) => uploadStatement(data), {
onSettled: () => {
refetch();
},
onError: (error) => {
handleError(error, "Error uploading. Please check your network and retry!!!");
},
onSuccess: (data) => {
console.log("Upload successful:", data.message);
},
});
};

Solution

  • The issue with your implementation is rather than you pass the mutation function directly, you passed a data, thus making it , Ideally, useMutation expect a mutationFn function (A function that performs an asynchronous task and returns a promise)

    export const useUploadStatement = () => {
      const { refetch } = useGetStageOneTransactions();
    
      return useMutation({
        mutationFn: async (data) => uploadStatement(data),
          onSettled: () => {
              refetch();
          },
          onError: (error) => {
              handleError(error, "Error uploading. Please check your network and retry!!!");
          },
          onSuccess: (data) => {
              console.log("Upload successful:", data.message);
          },
      })
    };
    

    See doc