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

App.tsx

223 lines5.7 KB

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