T
TanStack4y ago
flat-fuchsia

Unhandled runtime error using useMutation hook

I am using useMutation hook to update my database records. I thought that useMutation hook handles the error with onError method, but instead I get unhandled runtime error, here is my code:
const updateDiary = async (updatedDiary: Day[], userId: string) => {
const { error } = await supabase
.from('current_diaries')
.update({ days: updatedDiary })
.eq('uid', userId);
// this throws unhandled error
if (error) {
throw new Error(`${error.message}: ${error.details}`);
}
};

export function useUpdateDiary() {
return useMutation({
mutationFn: async ({
updatedDiary,
userId
}: {
updatedDiary: Day[];
userId: string;
}) => {
updateDiary(updatedDiary, userId);
},
onSuccess: () => {
toast.success('Day updated');
},
// this is not called on error
onError: () => {
toast.error(
"We couldn't save your diary please check your internet connection!"
);
}
});
}
const updateDiary = async (updatedDiary: Day[], userId: string) => {
const { error } = await supabase
.from('current_diaries')
.update({ days: updatedDiary })
.eq('uid', userId);
// this throws unhandled error
if (error) {
throw new Error(`${error.message}: ${error.details}`);
}
};

export function useUpdateDiary() {
return useMutation({
mutationFn: async ({
updatedDiary,
userId
}: {
updatedDiary: Day[];
userId: string;
}) => {
updateDiary(updatedDiary, userId);
},
onSuccess: () => {
toast.success('Day updated');
},
// this is not called on error
onError: () => {
toast.error(
"We couldn't save your diary please check your internet connection!"
);
}
});
}
No description
5 Replies
plain-purple
plain-purple4y ago
you're not showing the whole code. are you calling mutate or mutateAsync ?
flat-fuchsia
flat-fuchsiaOP4y ago
Sorry, yes I'm calling it with mutate:
const { mutate } = useUpdateDiary();
...///
mutate({ updatedDiary: updatedDiaryForSetQuery, userId: user.id });
const { mutate } = useUpdateDiary();
...///
mutate({ updatedDiary: updatedDiaryForSetQuery, userId: user.id });
plain-purple
plain-purple4y ago
ah, I see the error., you're not returning the promise from the mutation function:
{
updateDiary(updatedDiary, userId);
},
{
updateDiary(updatedDiary, userId);
},
flat-fuchsia
flat-fuchsiaOP4y ago
Thanks, it works now! Can I ask, why it was throwing error, I know I wasn't returning the function, but it was still running?
plain-purple
plain-purple4y ago
because mutate can only catch errors from the promise it receives

Did you find this page helpful?