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