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

index.jsx

135 lines3.6 KB

1/* eslint-disable jsx-a11y/anchor-is-valid */
2import React from 'react'
3import ReactDOM from 'react-dom/client'
4import axios from 'axios'
5import {
6 useQuery,
7 useQueryClient,
8 QueryClient,
9 QueryClientProvider,
10} from '@tanstack/react-query'
11import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
12​
13// Define a default query function that will receive the query key
14const defaultQueryFn = async ({ queryKey }) => {
15 const { data } = await axios.get(
16 `https://jsonplaceholder.typicode.com${queryKey[0]}`,
17 )
18 return data
20​
21// provide the default query function to your app via the query client
22const queryClient = new QueryClient({
23 defaultOptions: {
24 queries: {
25 queryFn: defaultQueryFn,
26 },
27 },
28})
29​
30function App() {
31 const [postId, setPostId] = React.useState(-1)
32​
33 return (
34 <QueryClientProvider client={queryClient}>
35 <p>
36 As you visit the posts below, you will notice them in a loading state
37 the first time you load them. However, after you return to this list and
38 click on any posts you have already visited again, you will see them
39 load instantly and background refresh right before your eyes!{' '}
40 <strong>
41 (You may need to throttle your network speed to simulate longer
42 loading sequences)
43 </strong>
44 </p>
45 {postId > -1 ? (
46 <Post postId={postId} setPostId={setPostId} />
47 ) : (
48 <Posts setPostId={setPostId} />
49 )}
50 <ReactQueryDevtools initialIsOpen />
51 </QueryClientProvider>
52 )
54​
55function Posts({ setPostId }) {
56 const queryClient = useQueryClient()
57​
58 // All you have to do now is pass a key!
59 const { status, data, error, isFetching } = useQuery({
60 queryKey: ['/posts'],
61 })
62​
63 return (
64 <div>
65 <h1>Posts</h1>
66 <div>
67 {status === 'pending' ? (
68 'Loading...'
69 ) : status === 'error' ? (
70 <span>Error: {error.message}</span>
71 ) : (
72 <>
73 <div>
74 {data.map((post) => (
75 <p key={post.id}>
76 <a
77 onClick={() => setPostId(post.id)}
78 href="#"
79 style={
80 // We can use the queryCache here to show bold links for
81 // ones that are cached
82 queryClient.getQueryData(['post', post.id])
83 ? {
84 fontWeight: 'bold',
85 color: 'green',
86 }
87 : {}
88 }
89 >
90 {post.title}
91 </a>
92 </p>
93 ))}
94 </div>
95 <div>{isFetching ? 'Background Updating...' : ' '}</div>
96 </>
97 )}
98 </div>
99 </div>
100 )
102​
103function Post({ postId, setPostId }) {
104 // You can even leave out the queryFn and just go straight into options
105 const { status, data, error, isFetching } = useQuery({
106 queryKey: [`/posts/${postId}`],
107 enabled: !!postId,
108 })
109​
110 return (
111 <div>
112 <div>
113 <a onClick={() => setPostId(-1)} href="#">
114 Back
115 </a>
116 </div>
117 {!postId || status === 'pending' ? (
118 'Loading...'
119 ) : status === 'error' ? (
120 <span>Error: {error.message}</span>
121 ) : (
122 <>
123 <h1>{data.title}</h1>
124 <div>
125 <p>{data.body}</p>
126 </div>
127 <div>{isFetching ? 'Background Updating...' : ' '}</div>
128 </>
129 )}
130 </div>
131 )
133​
134const rootElement = document.getElementById('root')
135ReactDOM.createRoot(rootElement).render(<App />)