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