Open History to see the last commit
1import React from 'react'
2import { 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β
21export default function Example() {
22 const queryClient = useQueryClient()
23 const rerender = React.useState(0)[1]
24 const [selectedChar, setSelectedChar] = React.useState(1)
25β
26 const charactersQuery = useQuery({
27 queryKey: ['characters'],
28 queryFn: getCharacters,
29 })
30β
31 const characterQuery = useQuery({
32 queryKey: ['character', selectedChar],
33 queryFn: () => getCharacter(selectedChar),
34 })
35β
36 return (
37 <div className="App">
38 <p>
39 Hovering over a character will prefetch it, and when it's been
40 prefetched it will turn <strong>bold</strong>. Clicking on a prefetched
41 character will show their stats below immediately.
42 </p>
43 <h2>Characters</h2>
44 {charactersQuery.isPending ? (
45 'Loading...'
46 ) : (
47 <>
48 <ul>
49 {charactersQuery.data?.results.map((char) => (
50 <li
51 key={char.id}
52 onClick={() => {
53 setSelectedChar(char.id)
54 }}
55 onMouseEnter={async () => {
56 await queryClient.prefetchQuery({
57 queryKey: ['character', char.id],
58 queryFn: () => getCharacter(char.id),
59 staleTime: 10 * 1000, // only prefetch if older than 10 seconds
60 })
61β
62 setTimeout(() => {
63 rerender({})
64 }, 1)
65 }}
66 >
67 <div
68 style={
69 queryClient.getQueryData(['character', char.id])
70 ? {
71 fontWeight: 'bold',
72 }
73 : {}
74 }
75 >
76 {char.id} - {char.name}
77 </div>
78 </li>
79 ))}
80 </ul>
81β
82 <h3>Selected Character</h3>
83 {characterQuery.isPending ? (
84 'Loading...'
85 ) : (
86 <>
87 <pre>{JSON.stringify(characterQuery.data, null, 2)}</pre>
88 </>
89 )}
90 <ReactQueryDevtools initialIsOpen />
91 </>
92 )}
93 </div>
94 )
95}