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

index.js

109 lines2.9 KB

1import React from 'react'
2import axios from 'axios'
3import {
4 useQuery,
5 useQueryClient,
6 QueryClient,
7 QueryClientProvider,
8} from '@tanstack/react-query'
9import { ReactQueryDevtools } from '@tanstack/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
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
24​
25const queryClient = new QueryClient()
26​
27export default function App() {
28 return (
29 <QueryClientProvider client={queryClient}>
30 <Example />
31 </QueryClientProvider>
32 )
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({
41 queryKey: ['characters'],
42 queryFn: getCharacters,
43 })
44​
45 const characterQuery = useQuery({
46 queryKey: ['character', selectedChar],
47 queryFn: () => getCharacter(selectedChar),
48 })
49​
50 return (
51 <div className="App">
52 <p>
53 Hovering over a character will prefetch it, and when it's been
54 prefetched it will turn <strong>bold</strong>. Clicking on a prefetched
55 character will show their stats below immediately.
56 </p>
57 <h2>Characters</h2>
58 {charactersQuery.isLoading ? (
59 'Loading...'
60 ) : (
61 <>
62 <ul>
63 {charactersQuery.data?.results.map((char) => (
64 <li
65 key={char.id}
66 onClick={() => {
67 setSelectedChar(char.id)
68 }}
69 onMouseEnter={async () => {
70 await queryClient.prefetchQuery({
71 queryKey: ['character', char.id],
72 queryFn: () => getCharacter(char.id),
73 staleTime: 10 * 1000, // only prefetch if older than 10 seconds
74 })
75​
76 setTimeout(() => {
77 rerender({})
78 }, 1)
79 }}
80 >
81 <div
82 style={
83 queryClient.getQueryData(['character', char.id])
84 ? {
85 fontWeight: 'bold',
86 }
87 : {}
88 }
89 >
90 {char.id} - {char.name}
91 </div>
92 </li>
93 ))}
94 </ul>
95​
96 <h3>Selected Character</h3>
97 {characterQuery.isLoading ? (
98 'Loading...'
99 ) : (
100 <>
101 <pre>{JSON.stringify(characterQuery.data, null, 2)}</pre>
102 </>
103 )}
104 <ReactQueryDevtools initialIsOpen />
105 </>
106 )}
107 </div>
108 )