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