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

App.js

221 lines5.7 KB

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