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