Mutation with useMutation Hook
Example of executing a POST request using the useMutation hook, and optimistically updating the UI.
import { useMutation, useQueryClient } from 'react-query';
import axios from 'axios';
Imports necessary hooks from react-query and axios for making HTTP requests.
const addTodo = async (newTodo) => {
const { data } = await axios.post('/api/todos', newTodo);
return data;
};
Defines an asynchronous function that makes a POST request to add a new todo item.
const Todos = () => {
const queryClient = useQueryClient();
const { mutate, isLoading, error } = useMutation(addTodo, {
onSuccess: () => {
// Invalidate and refetch
queryClient.invalidateQueries('todos');
},
});
Sets up the useMutation hook with the addTodo function and invalidates the todos query on success to refetch the todos list.
const handleSubmit = (newTodo) => {
mutate(newTodo);
};
if (isLoading) return 'Submitting...';
if (error) return 'An error occurred: ' + error.message;
return (<button onClick={() => handleSubmit({ text: 'New Todo' })}>Add Todo</button>);
};
Defines a handleSubmit function that uses the mutate function from useMutation to submit a new todo, shows loading and error feedback, and renders an Add Todo button.