T
TanStack2y ago
mere-teal

mutateAsync vs mutate with options. What's the difference?

The docs on this page: https://tanstack.com/query/latest/docs/framework/react/guides/mutations#promises say "Use mutateAsync instead of mutate to get a promise which will resolve on success or throw on an error. This can for example be used to compose side effects." with the following code as an example:
const mutation = useMutation({ mutationFn: addTodo })
try {
const todo = await mutation.mutateAsync(todo)
console.log(todo)
} catch (error) {
console.error(error)
} finally {
console.log('done')
}
const mutation = useMutation({ mutationFn: addTodo })
try {
const todo = await mutation.mutateAsync(todo)
console.log(todo)
} catch (error) {
console.error(error)
} finally {
console.log('done')
}
But given that you can pass options to the mutate function, wont this code produce the same results?:
const mutation = useMutation({ mutationFn: addTodo });
mutation.mutate(todo, {
onSuccess: (data) => {
console.log(data);
},
onError: (error) => {
console.error(error);
},
onSettled: () => {
console.log("done");
},
});
const mutation = useMutation({ mutationFn: addTodo });
mutation.mutate(todo, {
onSuccess: (data) => {
console.log(data);
},
onError: (error) => {
console.error(error);
},
onSettled: () => {
console.log("done");
},
});
Is there any meaningful difference? Thanks!
2 Replies
genetic-orange
genetic-orange2y ago
I think you may be in the wrong channel here. You probably want to ping the folks over in #react-query-questions
mere-teal
mere-tealOP2y ago
LOL i idk how i clicked the wrong one haha thanks

Did you find this page helpful?