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

index.tsx

99 lines2.5 KB

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