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