()
| 31 | }) |
| 32 | |
| 33 | function Example() { |
| 34 | const queryClient = useQueryClient() |
| 35 | const [text, setText] = React.useState('') |
| 36 | const { isFetching, ...queryInfo } = useQuery(todoListOptions) |
| 37 | |
| 38 | const addTodoMutation = useMutation({ |
| 39 | mutationFn: async (newTodo: string) => { |
| 40 | const response = await fetch('/api/data', { |
| 41 | method: 'POST', |
| 42 | body: JSON.stringify({ text: newTodo }), |
| 43 | headers: { 'Content-Type': 'application/json' }, |
| 44 | }) |
| 45 | return await response.json() |
| 46 | }, |
| 47 | // When mutate is called: |
| 48 | onMutate: async (newTodo, context) => { |
| 49 | setText('') |
| 50 | // Cancel any outgoing refetch |
| 51 | // (so they don't overwrite our optimistic update) |
| 52 | await context.client.cancelQueries(todoListOptions) |
| 53 | |
| 54 | // Snapshot the previous value |
| 55 | const previousTodos = context.client.getQueryData( |
| 56 | todoListOptions.queryKey, |
| 57 | ) |
| 58 | |
| 59 | // Optimistically update to the new value |
| 60 | if (previousTodos) { |
| 61 | context.client.setQueryData(todoListOptions.queryKey, { |
| 62 | ...previousTodos, |
| 63 | items: [ |
| 64 | ...previousTodos.items, |
| 65 | { id: Math.random().toString(), text: newTodo }, |
| 66 | ], |
| 67 | }) |
| 68 | } |
| 69 | |
| 70 | return { previousTodos } |
| 71 | }, |
| 72 | // If the mutation fails, |
| 73 | // use the result returned from onMutate to roll back |
| 74 | onError: (err, variables, onMutateResult, context) => { |
| 75 | if (onMutateResult?.previousTodos) { |
| 76 | context.client.setQueryData<Todos>( |
| 77 | ['todos'], |
| 78 | onMutateResult.previousTodos, |
| 79 | ) |
| 80 | } |
| 81 | }, |
| 82 | // Always refetch after error or success: |
| 83 | onSettled: (data, error, variables, onMutateResult, context) => |
| 84 | context.client.invalidateQueries({ queryKey: ['todos'] }), |
| 85 | }) |
| 86 | |
| 87 | return ( |
| 88 | <div> |
| 89 | <p> |
| 90 | In this example, new items can be created using a mutation. The new item |
nothing calls this directly
no test coverage detected
searching dependent graphs…