Other React Query Functionalities
Learn using React Query’s useMutation for server mutations, handle loading states, and efficiently update cached data with onSuccess.
We'll cover the following...
We can’t use React Query in our example app to mutate data on the server because our backend is not robust enough. In a real-life application, we would most probably use an API that accepts a POST
request just as well as a GET
request. In these cases, we would be able to change data with the help of React Query.
The useMutation
hook
In order to do so, we are provided with another specialized hook: useMutation
. Here’s what this hook would look like if we could use it for the favorited images:
// Define a mutation using useMutation for posting new imagesconst imageListMutation = useMutation((newImage) => {return fetch('/john_doe/likedImages', { method: 'POST', body: newImage });});
The preceding function is very simple. It wraps a fetch
call in a React Query utility. This utility offers us a few things, such as the fact that it has the following states:
isIdle
isLoading
isError
isSuccess
...