Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

index.js

71 lines1.9 KB

1import React from 'react'
2import axios from 'axios'
3import { useQuery, queryCache } from 'react-query'
4import { ReactQueryDevtools } from '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
11​
12const getCharacter = async (key, 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
19​
20export default function App() {
21 const [selectedChar, setSelectedChar] = React.useState(1)
22​
23 const { data } = useQuery('characters', getCharacters)
24​
25 const { data: selectedData } = useQuery(
26 ['character', selectedChar],
27 getCharacter
28 )
29​
30 const prefetchNext = async id => {
31 queryCache.prefetchQuery(['character', id + 1], getCharacter, {
32 staleTime: 5 * 60 * 1000,
33 })
34​
35 queryCache.prefetchQuery(['character', id - 1], getCharacter, {
36 staleTime: 5 * 60 * 1000,
37 })
38 }
39​
40 return (
41 <div className="App">
42 <p>
43 When selecting a character (eg. 12) it will also prefetch the sibling
44 characters, too (eg. 11 and 13). When selecting one of the siblings
45 after that (eg. 13), it will be displayed immediately and also refetched
46 in the background.
47 </p>
48 <h2>Characters</h2>
49 <ul>
50 {data?.results.map(char => (
51 <li
52 key={char.id}
53 onClick={() => {
54 setSelectedChar(char.id)
55 prefetchNext(char.id)
56 }}
57 >
58 <div>
59 {char.id} - {char.name}
60 </div>
61 </li>
62 ))}
63 </ul>
64 <h3>Selected Character</h3>
65 <p>
66 {selectedData?.name} ({selectedData?.status})
67 </p>
68 <ReactQueryDevtools />
69 </div>
70 )