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

index.tsx

129 lines3.0 KB

1import React from 'react'
2import {
3 noop,
4 queryOptions,
5 useQuery,
6 useQueryClient,
7} from '@tanstack/react-query'
8import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
9​
10type Character = {
11 id: number
12 name: string
14​
15const getCharacters = async (): Promise<{
16 results: Array<Character>
17}> => {
18 await new Promise((r) => setTimeout(r, 500))
19 const response = await fetch('https://rickandmortyapi.com/api/character/')
20 if (!response.ok) throw new Error('Failed to fetch characters')
21 return await response.json()
23​
24const getCharacter = async (selectedChar: number): Promise<Character> => {
25 await new Promise((r) => setTimeout(r, 500))
26 const response = await fetch(
27 `https://rickandmortyapi.com/api/character/${selectedChar}`,
28 )
29 if (!response.ok) throw new Error('Failed to fetch character')
30 return await response.json()
32​
33const charactersQueryOptions = queryOptions({
34 queryKey: ['characters'],
35 queryFn: getCharacters,
36})
37​
38const characterQueryOptions = (id: number) =>
39 queryOptions({
40 queryKey: ['character', id],
41 queryFn: () => getCharacter(id),
42 })
43​
44function CharacterItem({
45 char,
46 onSelect,
47}: {
48 char: Character
49 onSelect: (id: number) => void
50}) {
51 const queryClient = useQueryClient()
52​
53 const { data } = useQuery({
54 ...characterQueryOptions(char.id),
55 enabled: false,
56 })
57​
58 return (
59 <li
60 onClick={() => {
61 onSelect(char.id)
62 }}
63 onMouseEnter={() => {
64 queryClient
65 .query({
66 ...characterQueryOptions(char.id),
67 staleTime: 10 * 1000, // only prefetch if older than 10 seconds
68 })
69 .catch(noop)
70 }}
71 >
72 <div
73 style={
74 data
75 ? {
76 fontWeight: 'bold',
77 }
78 : {}
79 }
80 >
81 {char.id} - {char.name}
82 </div>
83 </li>
84 )
86​
87export default function Example() {
88 const [selectedChar, setSelectedChar] = React.useState(1)
89​
90 const charactersQuery = useQuery(charactersQueryOptions)
91​
92 const characterQuery = useQuery(characterQueryOptions(selectedChar))
93​
94 return (
95 <div className="App">
96 <p>
97 Hovering over a character will prefetch it, and when it's been
98 prefetched it will turn <strong>bold</strong>. Clicking on a prefetched
99 character will show their stats below immediately.
100 </p>
101 <h2>Characters</h2>
102 {charactersQuery.isPending ? (
103 'Loading...'
104 ) : (
105 <>
106 <ul>
107 {charactersQuery.data?.results.map((char) => (
108 <CharacterItem
109 key={char.id}
110 char={char}
111 onSelect={setSelectedChar}
112 />
113 ))}
114 </ul>
115​
116 <h3>Selected Character</h3>
117 {characterQuery.isPending ? (
118 'Loading...'
119 ) : (
120 <>
121 <pre>{JSON.stringify(characterQuery.data, null, 2)}</pre>
122 </>
123 )}
124 <ReactQueryDevtools initialIsOpen />
125 </>
126 )}
127 </div>
128 )