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