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