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