diff --git a/docs/framework/react/guides/mutations.md b/docs/framework/react/guides/mutations.md index c7b71c46f6..55484c7ee6 100644 --- a/docs/framework/react/guides/mutations.md +++ b/docs/framework/react/guides/mutations.md @@ -10,34 +10,45 @@ Here's an example of a mutation that adds a new todo to the server: [//]: # 'Example' ```tsx -function App() { +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' +import axios from 'axios' + +function TodoApp() { + const queryClient = useQueryClient() + + // 1. Fetch the existing todos list + const { data: todos, isLoading } = useQuery({ + queryKey: ['todos'], + queryFn: () => axios.get('/todos').then((res) => res.data), + }) + + // 2. Create the mutation and invalidate the list on success const mutation = useMutation({ - mutationFn: (newTodo) => { - return axios.post('/todos', newTodo) + mutationFn: (newTodo) => axios.post('/todos', newTodo), + onSuccess: () => { + // This forces useQuery to refetch and pull the updated list automatically + queryClient.invalidateQueries({ queryKey: ['todos'] }) }, }) + if (isLoading) return 'Loading todos...' + return (
- {mutation.isPending ? ( - 'Adding todo...' - ) : ( - <> - {mutation.isError ? ( -
An error occurred: {mutation.error.message}
- ) : null} - - {mutation.isSuccess ?
Todo added!
: null} - - - - )} + + +
) }