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

Home.tsx

93 lines2.5 KB

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