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