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, 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 <Movies />
68 <SolidQueryDevtools initialIsOpen />
69 </PersistQueryClientProvider>
70 )
71}
72β
73function Movies() {
74 const [page, setPage] = createSignal<
75 { type: 'list' } | { type: 'detail'; movieId: string }
76 >({ type: 'list' })
77β
78 return (
79 <Switch>
80 <Match when={page().type === 'list'}>
81 <List
82 onSelectMovie={(movieId) => setPage({ type: 'detail', movieId })}
83 />
84 </Match>
85 <Match when={page().type === 'detail'}>
86 <Detail
87 movieId={(page() as { type: 'detail'; movieId: string }).movieId}
88 onBack={() => setPage({ type: 'list' })}
89 />
90 </Match>
91 </Switch>
92 )
93}
94β
95function List(props: { onSelectMovie: (movieId: string) => void }) {
96 const moviesQuery = useQuery(() => ({
97 queryKey: movieKeys.list(),
98 queryFn: api.fetchMovies,
99 }))
100β
101 return (
102 <Switch>
103 <Match when={moviesQuery.isLoading}>Loading...</Match>
104 <Match when={moviesQuery.data}>
105 <div>
106 <h1>Movies</h1>
107 <p>
108 Try to mock offline behavior with the button in the devtools. You
109 can navigate around as long as there is already data in the cache.
110 You'll get a refetch as soon as you go online again.
111 </p>
112 <ul>
113 <For each={moviesQuery.data!.movies}>
114 {(movie) => (
115 <li>
116 <a
117 href="#"
118 onClick={(e) => {
119 e.preventDefault()
120 props.onSelectMovie(movie.id)
121 }}
122 >
123 {movie.title}
124 </a>
125 </li>
126 )}
127 </For>
128 </ul>
129 <div>
130 Updated at: {new Date(moviesQuery.data!.ts).toLocaleTimeString()}
131 </div>
132 <Show when={moviesQuery.isFetching}>
133 <div>fetching...</div>
134 </Show>
135 </div>
136 </Match>
137 </Switch>
138 )
139}
140β
141function Detail(props: { movieId: string; onBack: () => void }) {
142 const { comment, setComment, updateMovie, movieQuery } = useMovie(
143 props.movieId,
144 )
145β
146 function submitForm(event: SubmitEvent) {
147 event.preventDefault()
148β
149 updateMovie.mutate({
150 id: props.movieId,
151 comment: comment(),
152 })
153 }
154β
155 return (
156 <Switch>
157 <Match when={movieQuery.isLoading}>Loading...</Match>
158 <Match when={movieQuery.data}>
159 <form onSubmit={submitForm}>
160 <a
161 href="#"
162 onClick={(e) => {
163 e.preventDefault()
164 props.onBack()
165 }}
166 >
167 Back
168 </a>
169 <h1>Movie: {movieQuery.data!.movie.title}</h1>
170 <p>
171 Try to mock offline behavior with the button in the devtools, then
172 update the comment. The optimistic update will succeed, but the
173 actual mutation will be paused and resumed once you go online again.
174 </p>
175 <p>
176 You can also reload the page, which will make the persisted mutation
177 resume, as you will be online again when you "come back".
178 </p>
179 <p>
180 <label>
181 Comment: <br />
182 <textarea
183 name="comment"
184 value={comment() ?? ''}
185 onInput={(event) => setComment(event.currentTarget.value)}
186 />
187 </label>
188 </p>
189 <button type="submit">Submit</button>
190 <div>
191 Updated at: {new Date(movieQuery.data!.ts).toLocaleTimeString()}
192 </div>
193 <Show when={movieQuery.isFetching}>
194 <div>fetching...</div>
195 </Show>
196 <div>
197 {updateMovie.isPaused
198 ? 'mutation paused - offline'
199 : updateMovie.isPending && 'updating...'}
200 </div>
201 </form>
202 </Match>
203 <Match when={movieQuery.isPaused}>
204 We're offline and have no data to show :(
205 </Match>
206 </Switch>
207 )
208}