MCPcopy Create free account
hub / github.com/TanStack/query / Example

Function Example

examples/react/prefetching/src/pages/index.tsx:21–95  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

19}
20
21export default function Example() {
22 const queryClient = useQueryClient()
23 const rerender = React.useState(0)[1]
24 const [selectedChar, setSelectedChar] = React.useState(1)
25
26 const charactersQuery = useQuery({
27 queryKey: ['characters'],
28 queryFn: getCharacters,
29 })
30
31 const characterQuery = useQuery({
32 queryKey: ['character', selectedChar],
33 queryFn: () => getCharacter(selectedChar),
34 })
35
36 return (
37 <div className="App">
38 <p>
39 Hovering over a character will prefetch it, and when it's been
40 prefetched it will turn <strong>bold</strong>. Clicking on a prefetched
41 character will show their stats below immediately.
42 </p>
43 <h2>Characters</h2>
44 {charactersQuery.isPending ? (
45 'Loading...'
46 ) : (
47 <>
48 <ul>
49 {charactersQuery.data?.results.map((char) => (
50 <li
51 key={char.id}
52 onClick={() => {
53 setSelectedChar(char.id)
54 }}
55 onMouseEnter={async () => {
56 await queryClient.prefetchQuery({
57 queryKey: ['character', char.id],
58 queryFn: () => getCharacter(char.id),
59 staleTime: 10 * 1000, // only prefetch if older than 10 seconds
60 })
61
62 setTimeout(() => {
63 rerender({})
64 }, 1)
65 }}
66 >
67 <div
68 style={
69 queryClient.getQueryData(['character', char.id])
70 ? {
71 fontWeight: 'bold',
72 }
73 : {}
74 }
75 >
76 {char.id} - {char.name}
77 </div>
78 </li>

Callers

nothing calls this directly

Calls 5

useQueryClientFunction · 0.90
useQueryFunction · 0.90
getCharacterFunction · 0.70
prefetchQueryMethod · 0.45
getQueryDataMethod · 0.45

Tested by

no test coverage detected