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 </Switch>
134 )
135}
136β
137function Detail(props: { movieId: string; onBack: () => void }) {
138 const { comment, setComment, updateMovie, movieQuery } = useMovie(
139 () => props.movieId,
140 )
141β
142 function submitForm(event: SubmitEvent) {
143 event.preventDefault()
144β
145 const currentComment = comment()
146 if (currentComment === undefined) {
147 return
148 }
149β
150 updateMovie.mutate({
151 id: props.movieId,
152 comment: currentComment,
153 })
154 }
155β
156 return (
157 <Switch>
158 <Match when={movieQuery.isLoading}>Loading...</Match>
159 <Match when={movieQuery.data}>
160 <form onSubmit={submitForm}>
161 <a
162 href="#"
163 onClick={(e) => {
164 e.preventDefault()
165 props.onBack()
166 }}
167 >
168 Back
169 </a>
170 <h1>Movie: {movieQuery.data!.movie.title}</h1>
171 <p>
172 Try to mock offline behavior with the button in the devtools, then
173 update the comment. The optimistic update will succeed, but the
174 actual mutation will be paused and resumed once you go online again.
175 </p>
176 <p>
177 You can also reload the page, which will make the persisted mutation
178 resume, as you will be online again when you "come back".
179 </p>
180 <p>
181 <label>
182 Comment: <br />
183 <textarea
184 name="comment"
185 value={comment() ?? ''}
186 onInput={(event) => setComment(event.currentTarget.value)}
187 />
188 </label>
189 </p>
190 <button type="submit">Submit</button>
191 <div>
192 Updated at: {new Date(movieQuery.data!.ts).toLocaleTimeString()}
193 </div>
194 <Show when={movieQuery.isFetching}>
195 <div>fetching...</div>
196 </Show>
197 <div>
198 {updateMovie.isPaused
199 ? 'mutation paused - offline'
200 : updateMovie.isPending && 'updating...'}
201 </div>
202 </form>
203 </Match>
204 <Match when={movieQuery.isPaused}>
205 We're offline and have no data to show :(
206 </Match>
207 </Switch>
208 )
209}