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β
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
57 .query({
58 queryKey: ['character', char.id],
59 queryFn: () => getCharacter(char.id),
60 staleTime: 10 * 1000, // only prefetch if older than 10 seconds
61 })
62 .catch(noop)
63β
64 setTimeout(() => {
65 rerender({})
66 }, 1)
67 }}
68 >
69 <div
70 style={
71 queryClient.getQueryData(['character', char.id])
72 ? {
73 fontWeight: 'bold',
74 }
75 : {}
76 }
77 >
78 {char.id} - {char.name}
79 </div>
80 </li>
81 ))}
82 </ul>
83β
84 <h3>Selected Character</h3>
85 {characterQuery.isPending ? (
86 'Loading...'
87 ) : (
88 <>
89 <pre>{JSON.stringify(characterQuery.data, null, 2)}</pre>
90 </>
91 )}
92 <ReactQueryDevtools initialIsOpen />
93 </>
94 )}
95 </div>
96 )
97}