|
| 1 | +import * as React from 'react' |
| 2 | +import axios, { AxiosError } from 'axios' |
| 3 | + |
| 4 | +import { |
| 5 | + useQuery, |
| 6 | + useQueryClient, |
| 7 | + useMutation, |
| 8 | + QueryClient, |
| 9 | + QueryClientProvider, |
| 10 | + UseQueryOptions, |
| 11 | +} from 'react-query' |
| 12 | +import { ReactQueryDevtools } from 'react-query-devtools' |
| 13 | + |
| 14 | +const client = new QueryClient() |
| 15 | + |
| 16 | +export default function App() { |
| 17 | + return ( |
| 18 | + <QueryClientProvider client={client}> |
| 19 | + <Example /> |
| 20 | + <TodoCounter /> |
| 21 | + <ReactQueryDevtools initialIsOpen /> |
| 22 | + </QueryClientProvider> |
| 23 | + ) |
| 24 | +} |
| 25 | + |
| 26 | +type Todos = { |
| 27 | + items: readonly { |
| 28 | + id: string |
| 29 | + text: string |
| 30 | + }[] |
| 31 | + ts: number |
| 32 | +} |
| 33 | + |
| 34 | +async function fetchTodos(): Promise<Todos> { |
| 35 | + const res = await axios.get('/api/data') |
| 36 | + return res.data |
| 37 | +} |
| 38 | + |
| 39 | +function useTodos<TData = Todos>( |
| 40 | + options?: UseQueryOptions<TData, AxiosError, Todos> |
| 41 | +) { |
| 42 | + return useQuery('todos', fetchTodos, options) |
| 43 | +} |
| 44 | + |
| 45 | +function TodoCounter() { |
| 46 | + // subscribe only to changes in the 'data' prop, which will be the |
| 47 | + // amount of todos because of the select function |
| 48 | + const counterQuery = useTodos({ |
| 49 | + select: data => data.items.length, |
| 50 | + notifyOnChangeProps: ['data'], |
| 51 | + }) |
| 52 | + |
| 53 | + React.useEffect(() => { |
| 54 | + console.log('rendering counter') |
| 55 | + }) |
| 56 | + |
| 57 | + return <div>TodoCounter: {counterQuery.data ?? 0}</div> |
| 58 | +} |
| 59 | + |
| 60 | +function Example() { |
| 61 | + const queryClient = useQueryClient() |
| 62 | + const [text, setText] = React.useState('') |
| 63 | + const { isFetching, ...queryInfo } = useTodos() |
| 64 | + |
| 65 | + const addTodoMutation = useMutation( |
| 66 | + newTodo => axios.post('/api/data', { text: newTodo }), |
| 67 | + { |
| 68 | + // When mutate is called: |
| 69 | + onMutate: async (newTodo: string) => { |
| 70 | + setText('') |
| 71 | + // Cancel any outgoing refetches (so they don't overwrite our optimistic update) |
| 72 | + await queryClient.cancelQueries('todos') |
| 73 | + |
| 74 | + // Snapshot the previous value |
| 75 | + const previousTodos = queryClient.getQueryData<Todos>('todos') |
| 76 | + |
| 77 | + // Optimistically update to the new value |
| 78 | + if (previousTodos) { |
| 79 | + queryClient.setQueryData<Todos>('todos', { |
| 80 | + ...previousTodos, |
| 81 | + items: [ |
| 82 | + ...previousTodos.items, |
| 83 | + { id: Math.random().toString(), text: newTodo }, |
| 84 | + ], |
| 85 | + }) |
| 86 | + } |
| 87 | + |
| 88 | + return { previousTodos } |
| 89 | + }, |
| 90 | + // If the mutation fails, use the context returned from onMutate to roll back |
| 91 | + onError: (err, variables, context) => { |
| 92 | + if (context?.previousTodos) { |
| 93 | + queryClient.setQueryData<Todos>('todos', context.previousTodos) |
| 94 | + } |
| 95 | + }, |
| 96 | + // Always refetch after error or success: |
| 97 | + onSettled: () => { |
| 98 | + queryClient.invalidateQueries('todos') |
| 99 | + }, |
| 100 | + } |
| 101 | + ) |
| 102 | + |
| 103 | + return ( |
| 104 | + <div> |
| 105 | + <p> |
| 106 | + In this example, new items can be created using a mutation. The new item |
| 107 | + will be optimistically added to the list in hopes that the server |
| 108 | + accepts the item. If it does, the list is refetched with the true items |
| 109 | + from the list. Every now and then, the mutation may fail though. When |
| 110 | + that happens, the previous list of items is restored and the list is |
| 111 | + again refetched from the server. |
| 112 | + </p> |
| 113 | + <form |
| 114 | + onSubmit={e => { |
| 115 | + e.preventDefault() |
| 116 | + addTodoMutation.mutate(text) |
| 117 | + }} |
| 118 | + > |
| 119 | + <input |
| 120 | + type="text" |
| 121 | + onChange={event => setText(event.target.value)} |
| 122 | + value={text} |
| 123 | + /> |
| 124 | + <button disabled={addTodoMutation.isLoading}>Create</button> |
| 125 | + </form> |
| 126 | + <br /> |
| 127 | + {queryInfo.isSuccess && ( |
| 128 | + <> |
| 129 | + <div> |
| 130 | + {/* The type of queryInfo.data will be narrowed because we check for isSuccess first */} |
| 131 | + Updated At: {new Date(queryInfo.data.ts).toLocaleTimeString()} |
| 132 | + </div> |
| 133 | + <ul> |
| 134 | + {queryInfo.data.items.map(todo => ( |
| 135 | + <li key={todo.id}>{todo.text}</li> |
| 136 | + ))} |
| 137 | + </ul> |
| 138 | + {isFetching && <div>Updating in background...</div>} |
| 139 | + </> |
| 140 | + )} |
| 141 | + {queryInfo.isLoading && 'Loading'} |
| 142 | + {queryInfo.error?.message} |
| 143 | + </div> |
| 144 | + ) |
| 145 | +} |
0 commit comments