sajad torkamani

In a nutshell

In React Query, mutations are used to create, update or delete server-side data. They are also used to perform server side-effects (e.g., call an endpoint that sends an email or that processes a payment).

An example mutation

function App() {
  // Unlike useQuery, useMutation doesn't run immediately.
  // You must invoke mutation.mutate()
  const mutation = useMutation(newTodo => {
    return axios.post('/todos', newTodo)
  })
 
  return (
    <div>
      {mutation.isLoading ? (
        'Adding todo...'
      ) : (
        <>
          {mutation.isError ? (
            <div>An error occurred: {mutation.error.message}</div>
          ) : null}
 
          {mutation.isSuccess ? <div>Todo added!</div> : null}
 
          <button
            onClick={() => {
              mutation.mutate({ id: new Date(), title: 'Do Laundry' })
            }}
          >
            Create Todo
          </button>
        </>
      )}
    </div>
  ) }

Mutation states

StateDescription
isLoadingThe mutation is currently executing.
isErrorThe mutation encountered an error.
isSuccessThe mutation was successful and mutation data is available.
isIdleThe mutation is currently idle or in a fresh state.

Mutation information

PropertyDescription
dataThe mutation data, available only if the mutation is in the isSuccess state.
errorThe error data, availably only if the mutation is in the isError state.

Mutation lifecycle hooks

You can pass several arguments to the useMutation hook to perform side-effects at particular stages of the mutation life cycle:

useMutation(addTodo, {
  onMutate: variables => {
    // A mutation is about to happen!
 
    // Optionally return a context containing data to use when for example rolling back
     return { id: 1 }
   },
   onError: (error, variables, context) => {
     // An error happened!
     console.log(`rolling back optimistic update with id ${context.id}`)
   },
   onSuccess: (data, variables, context) => {
     // Boom baby!
   },
   onSettled: (data, error, variables, context) => {
     // Error or success... doesn't matter!
   },
 })

Other notes

  • Mutations can become a powerful tool when you use it with the onSuccess and invalidateQueries methods to invalidate the query cache after updating server data.

Sources

Leave a comment

Your email address will not be published. Required fields are marked *