Open History to see the last commit
1import { For, Loading, Match, Show, Switch, createSignal } from 'solid-js'
2import { MutationCache, QueryClient, useQuery } from '@tanstack/solid-query'
3import { SolidQueryDevtools } from '@tanstack/solid-query-devtools'
4import { PersistQueryClientProvider } from '@tanstack/solid-query-persist-client'
5import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister'
6β
7import * as api from './api'
8import { movieKeys, useMovie } from './movies'
9β
10const persister = createAsyncStoragePersister({
11 storage: window.localStorage,
12})
13β
14const queryClient = new QueryClient({
15 defaultOptions: {
16 queries: {
17 gcTime: 1000 * 60 * 60 * 24, // 24 hours
18 staleTime: 2000,
19 retry: 0,
20 },
21 },
22 // configure global cache callbacks to show notifications
23 mutationCache: new MutationCache({
24 onSuccess: (data: any) => {
25 showNotification(data.message, 'success')
26 },
27 onError: (error) => {
28 showNotification(error.message, 'error')
29 },
30 }),
31})
32β
33// we need a default mutation function so that paused mutations can resume after a page reload
34queryClient.setMutationDefaults(movieKeys.all(), {
35 mutationFn: async ({ id, comment }: { id: string; comment: string }) => {
36 // to avoid clashes with our optimistic update when an offline mutation continues
37 await queryClient.cancelQueries({ queryKey: movieKeys.detail(id) })
38 return api.updateMovie(id, comment)
39 },
40})
41β
42function showNotification(message: string, type: 'success' | 'error') {
43 const el = document.createElement('div')
44 el.style.cssText = `
45 position: fixed; top: 16px; right: 16px; z-index: 9999;
46 padding: 12px 24px; border-radius: 4px; color: white;
47 background: ${type === 'success' ? '#22c55e' : '#ef4444'};
48 animation: fadeIn 0.3s ease-in;
49 `
50 el.textContent = message
51 document.body.appendChild(el)
52 setTimeout(() => el.remove(), 3000)
53}
54β
55export default function App() {
56 return (
57 <PersistQueryClientProvider
58 client={queryClient}
59 persistOptions={{ persister }}
60 onSuccess={() => {
61 // resume mutations after initial restore from localStorage was successful
62 queryClient.resumePausedMutations().then(() => {
63 queryClient.invalidateQueries()
64 })
65 }}
66 >
67 <Loading fallback={<div>Loading...</div>}>
68 <Movies />
69 </Loading>
70 <SolidQueryDevtools initialIsOpen />
71 </PersistQueryClientProvider>
72 )
73}
74β
75function Movies() {
76 const [page, setPage] = createSignal<
77 { type: 'list' } | { type: 'detail'; movieId: string }
78 >({ type: 'list' })
79β
80 return (
81 <Switch>
82 <Match when={page().type === 'list'}>
83 <List
84 onSelectMovie={(movieId) => setPage({ type: 'detail', movieId })}
85 />
86 </Match>
87 <Match when={page().type === 'detail'}>
88 <Detail
89 movieId={(page() as { type: 'detail'; movieId: string }).movieId}
90 onBack={() => setPage({ type: 'list' })}
91 />
92 </Match>
93 </Switch>
94 )
95}
96β
97function List(props: { onSelectMovie: (movieId: string) => void }) {
98 const moviesQuery = useQuery(() => ({
99 queryKey: movieKeys.list(),
100 queryFn: api.fetchMovies,
101 }))
102β
103 return (
104 <Switch>
105 <Match when={moviesQuery.isLoading}>Loading...</Match>
106 <Match when={moviesQuery.data}>
107 <div>
108 <h1>Movies</h1>
109 <p>
110 Try to mock offline behavior with the button in the devtools. You
111 can navigate around as long as there is already data in the cache.
112 You'll get a refetch as soon as you go online again.
113 </p>
114 <ul>
115 <For each={moviesQuery.data!.movies}>
116 {(movieAccessor) => {
117 const movie =
118 typeof movieAccessor === 'function'
119 ? (movieAccessor as any)()
120 : movieAccessor
121 return (
122 <li>
123 <a
124 href="#"
125 onClick={(e) => {
126 e.preventDefault()
127 props.onSelectMovie(movie.id)
128 }}
129 >
130 {movie.title}
131 </a>
132 </li>
133 )
134 }}
135 </For>
136 </ul>
137 <div>
138 Updated at: {new Date(moviesQuery.data!.ts).toLocaleTimeString()}
139 </div>
140 <Show when={moviesQuery.isFetching}>
141 <div>fetching...</div>
142 </Show>
143 </div>
144 </Match>
145 </Switch>
146 )
147}
148β
149function Detail(props: { movieId: string; onBack: () => void }) {
150 const { comment, setComment, updateMovie, movieQuery } = useMovie(
151 props.movieId,
152 )
153β
154 function submitForm(event: SubmitEvent) {
155 event.preventDefault()
156β
157 updateMovie.mutate({
158 id: props.movieId,
159 comment: comment(),
160 })
161 }
162β
163 return (
164 <Switch>
165 <Match when={movieQuery.isLoading}>Loading...</Match>
166 <Match when={movieQuery.data}>
167 <form onSubmit={submitForm}>
168 <a
169 href="#"
170 onClick={(e) => {
171 e.preventDefault()
172 props.onBack()
173 }}
174 >
175 Back
176 </a>
177 <h1>Movie: {movieQuery.data!.movie.title}</h1>
178 <p>
179 Try to mock offline behavior with the button in the devtools, then
180 update the comment. The optimistic update will succeed, but the
181 actual mutation will be paused and resumed once you go online again.
182 </p>
183 <p>
184 You can also reload the page, which will make the persisted mutation
185 resume, as you will be online again when you "come back".
186 </p>
187 <p>
188 <label>
189 Comment: <br />
190 <textarea
191 name="comment"
192 value={comment() ?? ''}
193 onInput={(event) => setComment(event.currentTarget.value)}
194 />
195 </label>
196 </p>
197 <button type="submit">Submit</button>
198 <div>
199 Updated at: {new Date(movieQuery.data!.ts).toLocaleTimeString()}
200 </div>
201 <Show when={movieQuery.isFetching}>
202 <div>fetching...</div>
203 </Show>
204 <div>
205 {updateMovie.isPaused
206 ? 'mutation paused - offline'
207 : updateMovie.isPending && 'updating...'}
208 </div>
209 </form>
210 </Match>
211 <Match when={movieQuery.isPaused}>
212 We're offline and have no data to show :(
213 </Match>
214 </Switch>
215 )
216}