Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

App.tsx

267 lines6.8 KB

1import * as React from 'react'
2import {
3 MutationCache,
4 QueryClient,
5 onlineManager,
6 useIsRestoring,
7 useMutation,
8 useQuery,
9} from '@tanstack/react-query'
10import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
11import { Toaster, toast } from 'react-hot-toast'
12import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client'
13import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister'
14import {
15 Link,
16 Outlet,
17 ReactLocation,
18 Router,
19 useMatch,
20} from '@tanstack/react-location'
21​
22import { moviesMutations, moviesQueries } from './services/movies/queries'
23​
24const persister = createAsyncStoragePersister({
25 storage: window.localStorage,
26})
27​
28const location = new ReactLocation()
29​
30const queryClient = new QueryClient({
31 defaultOptions: {
32 queries: {
33 gcTime: 24 * 60 * 60 * 1000, // 24 hours
34 staleTime: 2000,
35 retry: 0,
36 },
37 },
38 // configure global cache callbacks to show error toast notifications
39 mutationCache: new MutationCache({
40 onError: (error) => {
41 toast.error(error.message)
42 },
43 }),
44})
45​
46// we need a default mutation function so that paused mutations can resume after a page reload
47queryClient.setMutationDefaults(moviesQueries.all(), {
48 ...moviesMutations.update(),
49 onSuccess: (data) => {
50 toast.success(data.message)
51 },
52})
53​
54export default function App() {
55 return (
56 <PersistQueryClientProvider
57 client={queryClient}
58 persistOptions={{ persister }}
59 onSuccess={() => {
60 // resume mutations after initial restore from localStorage was successful
61 queryClient.resumePausedMutations().then(() => {
62 queryClient.invalidateQueries()
63 })
64 }}
65 >
66 <Movies />
67 <ReactQueryDevtools initialIsOpen />
68 </PersistQueryClientProvider>
69 )
71​
72function Movies() {
73 const isRestoring = useIsRestoring()
74 return (
75 <Router
76 location={location}
77 routes={[
78 {
79 path: '/',
80 element: <List />,
81 },
82 {
83 path: ':movieId',
84 element: <Detail />,
85 loader: async ({ params: { movieId } }) =>
86 queryClient.getQueryData(moviesQueries.detail(movieId).queryKey) ??
87 // do not load if we are offline or hydrating because it returns a promise that is pending until we go online again
88 // we just let the Detail component handle it
89 (onlineManager.isOnline() && !isRestoring
90 ? queryClient.query(moviesQueries.detail(movieId))
91 : {}),
92 },
93 ]}
94 >
95 <Outlet />
96 <Toaster />
97 </Router>
98 )
100​
101function List() {
102 const moviesQuery = useQuery(moviesQueries.list())
103​
104 if (moviesQuery.isLoading) {
105 return 'Loading...'
106 }
107​
108 if (moviesQuery.data) {
109 return (
110 <div>
111 <h1>Movies</h1>
112 <p>
113 Try to mock offline behavior with the button in the devtools. You can
114 navigate around as long as there is already data in the cache. You'll
115 get a refetch as soon as you go online again.
116 </p>
117 <ul>
118 {moviesQuery.data.movies.map((movie) => (
119 <li key={movie.id}>
120 <Link to={`./${movie.id}`} preload={1}>
121 {movie.title}
122 </Link>
123 </li>
124 ))}
125 </ul>
126 <div>
127 Updated at: {new Date(moviesQuery.data.ts).toLocaleTimeString()}
128 </div>
129 <div>{moviesQuery.isFetching && 'fetching...'}</div>
130 </div>
131 )
132 }
133​
134 if (moviesQuery.isError) {
135 return (
136 <div>
137 <h1>Couldn't load movies!</h1>
138 <div>{moviesQuery.error.message}</div>
139 </div>
140 )
141 }
142​
143 // query will be in 'idle' fetchStatus while restoring from localStorage
144 return null
146​
147function Detail() {
148 const {
149 params: { movieId },
150 } = useMatch()
151 const movieQuery = useQuery(moviesQueries.detail(movieId))
152​
153 const [commentDraft, setCommentDraft] = React.useState<string | undefined>()
154​
155 const updateMovie = useMutation({
156 ...moviesMutations.update(),
157 mutationKey: moviesQueries.detail(movieId).queryKey,
158 onMutate: async (variables) => {
159 await queryClient.cancelQueries({
160 queryKey: moviesQueries.detail(movieId).queryKey,
161 })
162 const { queryKey } = moviesQueries.detail(movieId)
163 const previousData = queryClient.getQueryData(queryKey)
164​
165 // remove local state so that server state is taken instead
166 setCommentDraft(undefined)
167​
168 queryClient.setQueryData(
169 queryKey,
170 (old) =>
171 old && {
172 ...old,
173 movie: {
174 ...old.movie,
175 comment: variables.comment,
176 },
177 },
178 )
179​
180 return { previousData }
181 },
182 onError: (_, __, onMutateResult) => {
183 queryClient.setQueryData(
184 moviesQueries.detail(movieId).queryKey,
185 onMutateResult?.previousData,
186 )
187 },
188 onSettled: () => {
189 queryClient.invalidateQueries({
190 queryKey: moviesQueries.detail(movieId).queryKey,
191 })
192 },
193 })
194​
195 const comment = commentDraft ?? movieQuery.data?.movie.comment
196​
197 if (movieQuery.isLoading) {
198 return 'Loading...'
199 }
200​
201 function submitForm(event: any) {
202 event.preventDefault()
203​
204 if (comment === undefined) {
205 return
206 }
207​
208 updateMovie.mutate({
209 id: movieId,
210 comment,
211 })
212 }
213​
214 if (movieQuery.data) {
215 return (
216 <form onSubmit={submitForm}>
217 <Link to="..">Back</Link>
218 <h1>Movie: {movieQuery.data.movie.title}</h1>
219 <p>
220 Try to mock offline behavior with the button in the devtools, then
221 update the comment. The optimistic update will succeed, but the actual
222 mutation will be paused and resumed once you go online again.
223 </p>
224 <p>
225 You can also reload the page, which will make the persisted mutation
226 resume, as you will be online again when you "come back".
227 </p>
228 <p>
229 <label>
230 Comment: <br />
231 <textarea
232 name="comment"
233 value={comment}
234 onChange={(event) => setCommentDraft(event.target.value)}
235 />
236 </label>
237 </p>
238 <button type="submit">Submit</button>
239 <div>
240 Updated at: {new Date(movieQuery.data.ts).toLocaleTimeString()}
241 </div>
242 <div>{movieQuery.isFetching && 'fetching...'}</div>
243 <div>
244 {updateMovie.isPaused
245 ? 'mutation paused - offline'
246 : updateMovie.isPending && 'updating...'}
247 </div>
248 </form>
249 )
250 }
251​
252 if (movieQuery.isError) {
253 return (
254 <div>
255 <Link to="..">Back</Link>
256 <h1>Couldn't load movie!</h1>
257 <div>{movieQuery.error.message}</div>
258 </div>
259 )
260 }
261​
262 if (movieQuery.isPaused) {
263 return "We're offline and have no data to show :("
264 }
265​
266 return null