Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

App.tsx

209 lines6.0 KB

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)
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 )
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 )
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 )
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 )