Open History to see the last commit
1import * as React from 'react'
2import ReactDOM from 'react-dom/client'
3import { QueryClient, useQuery, useQueryClient } from '@tanstack/react-query'
4import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client'
5import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister'
6import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
7β
8const queryClient = new QueryClient({
9 defaultOptions: {
10 queries: {
11 gcTime: 1000 * 60 * 60 * 24, // 24 hours
12 },
13 },
14})
15β
16const persister = createAsyncStoragePersister({
17 storage: window.localStorage,
18})
19β
20type Post = {
21 id: number
22 title: string
23 body: string
24}
25β
26function usePosts() {
27 return useQuery({
28 queryKey: ['posts'],
29 queryFn: async (): Promise<Array<Post>> => {
30 const response = await fetch('https://jsonplaceholder.typicode.com/posts')
31 if (!response.ok) throw new Error('Failed to fetch posts')
32 return await response.json()
33 },
34 })
35}
36β
37function Posts({
38 setPostId,
39}: {
40 setPostId: React.Dispatch<React.SetStateAction<number>>
41}) {
42 const queryClient = useQueryClient()
43 const { status, data, error, isFetching } = usePosts()
44β
45 return (
46 <div>
47 <h1>Posts</h1>
48 <div>
49 {status === 'pending' ? (
50 'Loading...'
51 ) : status === 'error' ? (
52 <span>Error: {error.message}</span>
53 ) : (
54 <>
55 <div>
56 {data.map((post) => (
57 <p key={post.id}>
58 <a
59 onClick={() => setPostId(post.id)}
60 href="#"
61 style={
62 // We can access the query data here to show bold links for
63 // ones that are cached
64 queryClient.getQueryData(['post', post.id])
65 ? {
66 fontWeight: 'bold',
67 color: 'green',
68 }
69 : {}
70 }
71 >
72 {post.title}
73 </a>
74 </p>
75 ))}
76 </div>
77 <div>{isFetching ? 'Background Updating...' : ' '}</div>
78 </>
79 )}
80 </div>
81 </div>
82 )
83}
84β
85const getPostById = async (id: number): Promise<Post> => {
86 const response = await fetch(
87 `https://jsonplaceholder.typicode.com/posts/${id}`,
88 )
89 if (!response.ok) throw new Error('Failed to fetch post')
90 return await response.json()
91}
92β
93function usePost(postId: number) {
94 return useQuery({
95 queryKey: ['post', postId],
96 queryFn: () => getPostById(postId),
97 enabled: !!postId,
98 })
99}
100β
101function Post({
102 postId,
103 setPostId,
104}: {
105 postId: number
106 setPostId: React.Dispatch<React.SetStateAction<number>>
107}) {
108 const { status, data, error, isFetching } = usePost(postId)
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 )
132}
133β
134function App() {
135 const [postId, setPostId] = React.useState(-1)
136β
137 return (
138 <PersistQueryClientProvider
139 client={queryClient}
140 persistOptions={{ persister }}
141 >
142 <p>
143 As you visit the posts below, you will notice them in a loading state
144 the first time you load them. However, after you return to this list and
145 click on any posts you have already visited again, you will see them
146 load instantly and background refresh right before your eyes!{' '}
147 <strong>
148 (You may need to throttle your network speed to simulate longer
149 loading sequences)
150 </strong>
151 </p>
152 {postId > -1 ? (
153 <Post postId={postId} setPostId={setPostId} />
154 ) : (
155 <Posts setPostId={setPostId} />
156 )}
157 <ReactQueryDevtools initialIsOpen />
158 </PersistQueryClientProvider>
159 )
160}
161β
162const rootElement = document.getElementById('root')
163if (!rootElement) throw new Error('Missing #root element')
164ReactDOM.createRoot(rootElement).render(<App />)