MCPcopy Create free account
hub / github.com/TanStack/query / Example

Function Example

examples/react/optimistic-updates-ui/src/pages/index.tsx:30–108  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

28}
29
30function Example() {
31 const queryClient = useQueryClient()
32 const [text, setText] = React.useState('')
33 const todoQuery = useTodos()
34
35 const addTodoMutation = useMutation({
36 mutationFn: async (newTodo: string) => {
37 const response = await fetch('/api/data', {
38 method: 'POST',
39 body: JSON.stringify({ text: newTodo }),
40 headers: { 'Content-Type': 'application/json' },
41 })
42 if (!response.ok) {
43 throw new Error('Something went wrong.')
44 }
45 return await response.json()
46 },
47 onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
48 })
49
50 return (
51 <div>
52 <p>
53 In this example, new items can be created using a mutation. The new item
54 will be optimistically added to the list in hopes that the server
55 accepts the item. If it does, the list is refetched with the true items
56 from the list. Every now and then, the mutation may fail though. When
57 that happens, the previous list of items is restored and the list is
58 again refetched from the server.
59 </p>
60 <form
61 onSubmit={(e) => {
62 e.preventDefault()
63 setText('')
64 addTodoMutation.mutate(text)
65 }}
66 >
67 <input
68 type="text"
69 onChange={(event) => setText(event.target.value)}
70 value={text}
71 />
72 <button disabled={addTodoMutation.isPending}>Create</button>
73 </form>
74 <br />
75 {todoQuery.isSuccess && (
76 <>
77 <div>
78 {/* The type of queryInfo.data will be narrowed because we check for isSuccess first */}
79 Updated At: {new Date(todoQuery.data.ts).toLocaleTimeString()}
80 </div>
81 <ul>
82 {todoQuery.data.items.map((todo) => (
83 <li key={todo.id}>{todo.text}</li>
84 ))}
85 {addTodoMutation.isPending && (
86 <li style={{ opacity: 0.5 }}>{addTodoMutation.variables}</li>
87 )}

Callers

nothing calls this directly

Calls 5

useQueryClientFunction · 0.90
useMutationFunction · 0.90
useTodosFunction · 0.85
invalidateQueriesMethod · 0.45
mutateMethod · 0.45

Tested by

no test coverage detected