T
TanStack3y ago
xenial-black

How to handle error from useMutation

Hi, i have this function that updates the post
export const updatePost = async (payload: MutationPayload) => {
let { error, data } = await supabase
.from("posts")
.update(payload.body)
.eq("id", payload.id)
.select("*, profiles(*)")
.single();

if (error) {
throw error;
}

return data;
};
export const updatePost = async (payload: MutationPayload) => {
let { error, data } = await supabase
.from("posts")
.update(payload.body)
.eq("id", payload.id)
.select("*, profiles(*)")
.single();

if (error) {
throw error;
}

return data;
};
And i created this hook
export const useUpdatePost = () => {
const queryClient = useQueryClient();
return useMutation((payload: MutationPayload) => updatePost(payload), {
onSuccess: (updatedPost: any) => {
queryClient.setQueryData(["posts"], (prev: any) =>
prev.map((post: Post) =>
post.id === updatedPost.id ? updatedPost : post
)
);
},
onError: (error: PostgrestError) => {
throw error;
},
});
};
export const useUpdatePost = () => {
const queryClient = useQueryClient();
return useMutation((payload: MutationPayload) => updatePost(payload), {
onSuccess: (updatedPost: any) => {
queryClient.setQueryData(["posts"], (prev: any) =>
prev.map((post: Post) =>
post.id === updatedPost.id ? updatedPost : post
)
);
},
onError: (error: PostgrestError) => {
throw error;
},
});
};
And then i'm using a try catch block with mutate, but it's not catching the error
try {
mutate(payload);
} catch (error) {
throw new Error("Erro");
}
try {
mutate(payload);
} catch (error) {
throw new Error("Erro");
}
1 Reply
foreign-sapphire
foreign-sapphire3y ago
There's no need to throw in onError. Also, mutate catches errors internally. You can use onError there or use mutateAsync : https://tkdodo.eu/blog/mastering-mutations-in-react-query#mutate-or-mutateasync
Mastering Mutations in React Query
Learn all about the concept of performing side effects on the server with React Query.

Did you find this page helpful?