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