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

App.tsx

224 lines5.5 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 errorElement: <MovieError />,
90 loader: async ({ params: { movieId } }) =>
91 queryClient.getQueryData(movieQueryOptions(movieId).queryKey) ??
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.query(movieQueryOptions(movieId))
96 : {}),
97 },
98 ]}
99 >
100 <Outlet />
101 <Toaster />
102 </Router>
103 )
105​
106function List() {
107 const moviesQuery = useQuery({
108 queryKey: movieKeys.list(),
109 queryFn: api.fetchMovies,
110 })
111​
112 if (moviesQuery.isLoading) {
113 return 'Loading...'
114 }
115​
116 if (moviesQuery.data) {
117 return (
118 <div>
119 <h1>Movies</h1>
120 <p>
121 Try to mock offline behaviour with the button in the devtools. You can
122 navigate around as long as there is already data in the cache. You'll
123 get a refetch as soon as you go online again.
124 </p>
125 <ul>
126 {moviesQuery.data.movies.map((movie) => (
127 <li key={movie.id}>
128 <Link to={`./${movie.id}`} preload={1}>
129 {movie.title}
130 </Link>
131 </li>
132 ))}
133 </ul>
134 <div>
135 Updated at: {new Date(moviesQuery.data.ts).toLocaleTimeString()}
136 </div>
137 <div>{moviesQuery.isFetching && 'fetching...'}</div>
138 </div>
139 )
140 }
141​
142 // query will be in 'idle' fetchStatus while restoring from localStorage
143 return null
145​
146function MovieError() {
147 const { error } = useMatch()
148​
149 return (
150 <div>
151 <Link to="..">Back</Link>
152 <h1>Couldn't load movie!</h1>
153 {error instanceof Error && <div>{error.message}</div>}
154 </div>
155 )
157​
158function Detail() {
159 const {
160 params: { movieId },
161 } = useMatch()
162 const { comment, setComment, updateMovie, movieQuery } = useMovie(movieId)
163​
164 if (movieQuery.isLoading) {
165 return 'Loading...'
166 }
167​
168 function submitForm(event: any) {
169 event.preventDefault()
170​
171 if (comment === undefined) {
172 return
173 }
174​
175 updateMovie.mutate({
176 id: movieId,
177 comment,
178 })
179 }
180​
181 if (movieQuery.data) {
182 return (
183 <form onSubmit={submitForm}>
184 <Link to="..">Back</Link>
185 <h1>Movie: {movieQuery.data.movie.title}</h1>
186 <p>
187 Try to mock offline behaviour with the button in the devtools, then
188 update the comment. The optimistic update will succeed, but the actual
189 mutation will be paused and resumed once you go online again.
190 </p>
191 <p>
192 You can also reload the page, which will make the persisted mutation
193 resume, as you will be online again when you "come back".
194 </p>
195 <p>
196 <label>
197 Comment: <br />
198 <textarea
199 name="comment"
200 value={comment}
201 onChange={(event) => setComment(event.target.value)}
202 />
203 </label>
204 </p>
205 <button type="submit">Submit</button>
206 <div>
207 Updated at: {new Date(movieQuery.data.ts).toLocaleTimeString()}
208 </div>
209 <div>{movieQuery.isFetching && 'fetching...'}</div>
210 <div>
211 {updateMovie.isPaused
212 ? 'mutation paused - offline'
213 : updateMovie.isPending && 'updating...'}
214 </div>
215 </form>
216 )
217 }
218​
219 if (movieQuery.isPaused) {
220 return "We're offline and have no data to show :("
221 }
222​
223 return null