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 })
98}
99β
100function Post({
101 postId,
102 setPostId,
103}: {
104 postId: number
105 setPostId: React.Dispatch<React.SetStateAction<number>>
106}) {
107 const { status, data, error, isFetching } = usePost(postId)
108β
109 return (
110 <div>
111 <div>
112 <a onClick={() => setPostId(-1)} href="#">
113 Back
114 </a>
115 </div>
116 {status === 'pending' ? (
117 'Loading...'
118 ) : status === 'error' ? (
119 <span>Error: {error.message}</span>
120 ) : (
121 <>
122 <h1>{data.title}</h1>
123 <div>
124 <p>{data.body}</p>
125 </div>
126 <div>{isFetching ? 'Background Updating...' : ' '}</div>
127 </>
128 )}
129 </div>
130 )
131}
132β
133function App() {
134 const [postId, setPostId] = React.useState(-1)
135β
136 return (
137 <PersistQueryClientProvider
138 client={queryClient}
139 persistOptions={{ persister }}
140 >
141 <p>
142 As you visit the posts below, you will notice them in a loading state
143 the first time you load them. However, after you return to this list and
144 click on any posts you have already visited again, you will see them
145 load instantly and background refresh right before your eyes!{' '}
146 <strong>
147 (You may need to throttle your network speed to simulate longer
148 loading sequences)
149 </strong>
150 </p>
151 {postId > -1 ? (
152 <Post postId={postId} setPostId={setPostId} />
153 ) : (
154 <Posts setPostId={setPostId} />
155 )}
156 <ReactQueryDevtools initialIsOpen />
157 </PersistQueryClientProvider>
158 )
159}
160β
161const rootElement = document.getElementById('root')
162if (!rootElement) throw new Error('Missing #root element')
163ReactDOM.createRoot(rootElement).render(<App />)