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

App.tsx

230 lines5.6 KB

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