I use react-query in my project, and I got a bug in my custom hook where I use useMutation
query. I have all my custom hooks for queries
in the file useApiData
and useUpdateCase
is one of them:
export const useUpdateCase = (caseId: number) => {
const queryClient = useQueryClient();
const [error, setError] = useState(undefined);
const mutation = useMutation({
mutationFn: (payload: UpdateCaseRequest): Promise<AxiosResponse<CaseDto>> =>
CASE_API.api.updateCase(caseId, payload),
onSuccess: (data) => {
queryClient.setQueryData(["case", caseId], data);
console.log("onSuccess");
setError(undefined);
},
onError: (error) => {
console.log("onError", error);
setError(error);
},
});
console.log("error", error);
console.log("mutation", mutation);
return { mutation, error };
};
Here in this custom hook, error is being logged properly, I am returning 503 with mock service worker:
rest.put(`${environment.url.case}/api/case/:caseId`, async (req, res, ctx) => {
const body = await req.json();
const existingCase = JSON.parse(localStorage.getItem(`case-${req.params.caseId}`));
const updatedCase = { ...existingCase, ...body };
const sucessHeaders = [
ctx.set("Content-Type", "application/json"),
ctx.status(200),
ctx.body(JSON.stringify(updatedCase)),
];
const errorHeaders = [
ctx.status(503),
ctx.json({
errorMessage: "Service Unavailable",
}),
];
const index = 1; //Math.random() < 0.9 ? 0 : 1;
const response = [sucessHeaders, errorHeaders];
// if (index === 0) {
// localStorage.setItem(`case-${req.params.caseId}`, JSON.stringify(updatedCase));
// }
return res(...response[index]);
}),
But, in the component where I am calling this custom hook from:
const updateCase = useUpdateCase(caseId);
console.log("updateCase", updateCase);
On error updateCase
is not updated here. Nothing is being logged while in the custom hook error is logged.
So, in my console, logs look like this:
updateCase {mutation: {…}, error: undefined} useApiData.tsx:48 error AxiosError {message: 'Request failed with status code 503', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …} useApiData.tsx:49 mutation {context: undefined, data: undefined, error: AxiosError, failureCount: 1, failureReason: AxiosError, …}
What am I doing wrong here, why is the updated value not being propagated to a component where it was called from?