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

index.tsx

87 lines2.5 KB

1import { ErrorBoundary, For, Suspense, createSignal } from 'solid-js'
2import { A } from '@solidjs/router'
3import { noop, useQuery, useQueryClient } from '@tanstack/solid-query'
4import type { Character } from '~/services/characters/types'
5import { charactersQueries } from '~/services/characters/queries'
6​
7function CharacterItem(props: {
8 char: Character
9 onSelect: (id: number) => void
10}) {
11 const queryClient = useQueryClient()
12​
13 const characterQuery = useQuery(() => ({
14 ...charactersQueries.detail(props.char.id),
15 enabled: false,
16 }))
17​
18 const prefetch = () => {
19 queryClient
20 .query({
21 ...charactersQueries.detail(props.char.id),
22 staleTime: 10 * 1000, // only prefetch if older than 10 seconds
23 })
24 .catch(noop)
25 }
26​
27 return (
28 <li onMouseEnter={prefetch} onFocusIn={prefetch}>
29 <button
30 type="button"
31 style={characterQuery.isSuccess ? { 'font-weight': 'bold' } : {}}
32 onClick={() => {
33 props.onSelect(props.char.id)
34 }}
35 >
36 {props.char.id} - {props.char.name}
37 </button>{' '}
38 <A href={`/character/${props.char.id}`}>details</A>
39 </li>
40 )
42​
43function SelectedCharacter(props: { id: number }) {
44 const characterQuery = useQuery(() => ({
45 ...charactersQueries.detail(props.id),
46 throwOnError: true,
47 }))
48​
49 return <pre>{JSON.stringify(characterQuery.data, null, 2)}</pre>
51​
52export default function Example() {
53 const [selectedChar, setSelectedChar] = createSignal(1)
54​
55 const charactersQuery = useQuery(() => ({
56 ...charactersQueries.list(),
57 throwOnError: true,
58 }))
59​
60 return (
61 <div class="App">
62 <p>
63 Hovering over a character will prefetch it, and when it's been
64 prefetched it will turn <strong>bold</strong>. Clicking on a prefetched
65 character will show their stats below immediately, and opening its
66 details page will render it without a loading state.
67 </p>
68 <h2>Characters</h2>
69 <ErrorBoundary fallback={(error) => <span>Error: {error.message}</span>}>
70 <Suspense fallback="Loading...">
71 <ul>
72 <For each={charactersQuery.data?.results}>
73 {(char) => (
74 <CharacterItem char={char} onSelect={setSelectedChar} />
75 )}
76 </For>
77 </ul>
78​
79 <h3>Selected Character</h3>
80 <Suspense fallback="Loading...">
81 <SelectedCharacter id={selectedChar()} />
82 </Suspense>
83 </Suspense>
84 </ErrorBoundary>
85 </div>
86 )