T
TanStack3y ago
eager-peach

mutation.isSuccess not working

I have a submit function that when called, I want to do a mutation. If a successfull mutation, I want to do some action and if error I want to do a different action. My code currently is not catching the mutation.isSuccess even though there are no errors.
const submit = async () => {
await mutation.mutateAsync({
promptId: "123",
content: entryText,
});
if (mutation.isSuccess) {
setSuccess(true);
} else if (mutation.isError) {
setSuccess(false);
}
};
const submit = async () => {
await mutation.mutateAsync({
promptId: "123",
content: entryText,
});
if (mutation.isSuccess) {
setSuccess(true);
} else if (mutation.isError) {
setSuccess(false);
}
};
3 Replies
conscious-sapphire
conscious-sapphire3y ago
Your function closes over the mutation values. This means the values won’t change until the component re-renders, at which point the conditions will never be reached as the function won’t be executed with the mutation in that state. Try using an onSuccess callback instead.
like-gold
like-gold3y ago
^ 🙌 It would look this this
const muation = useMutation({
mutationFn: apiCallFunc,
onSuccess: () => { setSuccess(true) },
onError: () => { setSuccess(false) }
});

const submit = async () => {
await mutation.mutateAsync({
promptId: '123',
content: entryText
});
};
const muation = useMutation({
mutationFn: apiCallFunc,
onSuccess: () => { setSuccess(true) },
onError: () => { setSuccess(false) }
});

const submit = async () => {
await mutation.mutateAsync({
promptId: '123',
content: entryText
});
};
conscious-sapphire
conscious-sapphire3y ago
Exactly, thanks Sean 🙂 I'd use the synchronous mutate function here too

Did you find this page helpful?