I am new to react query.
I found out that using useQuery can reduce requests by caching.
But it's hard to understand why I use useMutation.
axios.post('/user', { name, ... })
.then(res => console.log(res))
.catch(err => console.log(err);
const { mutate, isLoading, ... } = useMutation(fetcher, {
onSuccess: (res) => {
console.log(res);
},
onError: (err) => {
console.log(err);
}
});
Both codes handle successful requests and errors.
Isn't queryClient.invalidateQueries('queryKey'); also covered by axios then() function?
What's the difference between the two?
Outside of returning useful mutation states (isPending, isSuccess, error), as of React Query v5 you can now track a mutation from another component, with help of useMutationState. In some cases this can eliminate the need for a store/context to expose these states to other components, or passing them down as props, as any component can just access any mutation with useMutationState, provided you specified the mutationKey
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With