Clarifications about useMutation
#344
-
I was hoping someone could clarify something for me. I'm not entirely sure what is the point of Is there any difference between the 3 versions below as far as react-query is concerned? v1 const [mutate] = useMutation(addTodo, {
onSuccess: () => {
queryCache.refetchQueries('todos');
queryCache.refetchQueries('reminders');
},
});
await mutate(todo); and v2 const [mutate] = useMutation(addTodo);
try {
await mutate(todo);
queryCache.refetchQueries('todos');
queryCache.refetchQueries('reminders');
}
catch {
// something went wrong
} and v3 try {
await addTodo(todo);
queryCache.refetchQueries('todos');
queryCache.refetchQueries('reminders');
}
catch {
// something went wrong
} Thanks for your help. |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 11 replies
-
Other useful features beyond this are:
|
Beta Was this translation helpful? Give feedback.
-
Thanks for the detailed explanation, much appreciated. I didn't realize that among other things Also, while, you're here and you're being kind to answer my questions, I'll go ahead and ask one more (sorry). I'm currently copying I'm sorry I know this is a bit general, but I would appreciate some expert guidance. |
Beta Was this translation helpful? Give feedback.
-
If you are copying data into state so that you can edit it as a draft for some mutation payload then that is expected. When you send off the mutation and it succeeds, you should refetch the original query that it affected, then if necessary, use the new response to again copy into your editable state. |
Beta Was this translation helpful? Give feedback.
-
@tannerlinsley Or probably better approach use const [formData, setFormData] = useState()
const { data } = useQuery(['login', formData], loginApi, {
enabled: !!formData
});
const handleLogin = useCallback((data) => {
setFormData(data)
}, []);
<form action="" onSubmit={handleLogin}>
...
</form> Then there is one more question, why do we need useMutation, if we could do anything with useQuery, and get cache by default? Thank you. |
Beta Was this translation helpful? Give feedback.
useMutation
is indeed built from similar control flow you have shown here, but it's built this way so that you can be more terse and declarative with your mutation-side effects where you declare your mutation logic instead of having to handle that control flow yourself in a try/catch/finally block. When you see an example like optimistic updates and rollbacks usingonMutate
,onError
andonSuccess
and all of the variable mapping that goes on between them, it's more clear that you would not want to write that on your own every time you need it, nor would I expect many to want to have to set up this logic on their own in some type of promise wrapper.Other useful features beyond this are: