Mutating Data with useMutation

In Tanstack Query, while useQuery is used for fetching and reading data, useMutation is used for creating, updating, or deleting data. Essentially, any API operations that have side effects.

useMutation gives you a way to interact with your server when you need to make changes to your data (like adding a new todo item). It also provides you with states and functions to handle the mutation lifecycle, such as when the mutation is loading, successful, or if an error occurred.

Here's a basic example of how you might use useMutation to add a new todo item:

import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import request from 'superagent'
// This is the function that will perform the POST request to add a new todo using superagent
const addTodo = async (newTodo: {title: string}) => {
try {
const response = await request
.post('https://jsonplaceholder.typicode.com/todos')
.send(newTodo)
return response.body
} catch (error) {
// Handle the error as needed, for example, by logging or displaying a message
// Throw the error to ensure useMutation's onError callback gets triggered
throw error
}
}
// This is our component that uses the useMutation hook
function AddTodo() {
const queryClient = useQueryClient();
const [todoText, setTodoText] = useState('' as string);
const mutation = useMutation({
mutationFn: addTodo,
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['todos']
});
},
});
const handleAddTodo = () => {
mutation.mutate({ title: todoText });
}
return (
<div>
<input
type="text"
value={todoText}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setTodoText(e.target.value)}
placeholder="Enter a new todo"
/>
<button onClick={handleAddTodo} disabled={mutation.isLoading}>
Add Todo
</button>
{mutation.isError ? (
<div>An error occurred: {mutation.error.message}</div>
) : null}
{mutation.isSuccess ? <div>Todo added!</div> : null}
</div>
)
}
export default AddTodo

In this example, we have an addTodo function that sends a POST request to an API to create a new todo item. We use the useMutation hook to call this function when the user clicks the "Add Todo" button.

The useMutation hook returns an object with properties and methods to manage the mutation's state and side effects:

  • mutate: A function to call to trigger the mutation.
  • isPending: A boolean indicating if the mutation is in progress (Previously isLoading.)
  • isError: A boolean indicating if the mutation encountered an error.
  • isSuccess: A boolean indicating if the mutation was successful.
  • error: An object containing error information if the mutation fails.

We also use the queryClient.invalidateQueries method to tell Tanstack Query to refetch the data for the 'todos' query after a successful mutation, ensuring the list is up-to-date.

Don't forget to wrap your application with QueryClientProvider and create a QueryClient instance.

And that's how you use useMutation with Tanstack Query in a React application to create, update, or delete data.