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

index.tsx

163 lines4.1 KB

1/* eslint-disable jsx-a11y/anchor-is-valid */
2import * as React from "react";
3import ReactDOM from "react-dom/client";
4import axios from "axios";
5import { useQuery, useQueryClient, QueryClient } from "react-query";
6import { PersistQueryClientProvider } from "react-query/persistQueryClient";
7import { createWebStoragePersister } from "react-query/createWebStoragePersister";
8import { ReactQueryDevtools } from "react-query/devtools";
9​
10const queryClient = new QueryClient({
11 defaultOptions: {
12 queries: {
13 cacheTime: 1000 * 60 * 60 * 24, // 24 hours
14 },
15 },
16});
17​
18const persister = createWebStoragePersister({
19 storage: window.localStorage,
20});
21​
22type Post = {
23 id: number;
24 title: string;
25 body: string;
26};
27​
28function usePosts() {
29 return useQuery(
30 ["posts"],
31 async (): Promise<Array<Post>> => {
32 const { data } = await axios.get(
33 "https://jsonplaceholder.typicode.com/posts"
34 );
35 return data;
36 }
37 );
39​
40function Posts({
41 setPostId,
42}: {
43 setPostId: React.Dispatch<React.SetStateAction<number>>;
44}) {
45 const queryClient = useQueryClient();
46 const { status, data, error, isFetching } = usePosts();
47​
48 return (
49 <div>
50 <h1>Posts</h1>
51 <div>
52 {status === "loading" ? (
53 "Loading..."
54 ) : error instanceof Error ? (
55 <span>Error: {error.message}</span>
56 ) : (
57 <>
58 <div>
59 {data?.map((post) => (
60 <p key={post.id}>
61 <a
62 onClick={() => setPostId(post.id)}
63 href="#"
64 style={
65 // We can access the query data here to show bold links for
66 // ones that are cached
67 queryClient.getQueryData(["post", post.id])
68 ? {
69 fontWeight: "bold",
70 color: "green",
71 }
72 : {}
73 }
74 >
75 {post.title}
76 </a>
77 </p>
78 ))}
79 </div>
80 <div>{isFetching ? "Background Updating..." : " "}</div>
81 </>
82 )}
83 </div>
84 </div>
85 );
87​
88const getPostById = async (id: number): Promise<Post> => {
89 const { data } = await axios.get(
90 `https://jsonplaceholder.typicode.com/posts/${id}`
91 );
92 return data;
93};
94​
95function usePost(postId: number) {
96 return useQuery(["post", postId], () => getPostById(postId), {
97 enabled: !!postId,
98 });
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 === "loading" ? (
118 "Loading..."
119 ) : error instanceof 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​
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 );
161​
162const rootElement = document.getElementById("root");
163ReactDOM.createRoot(rootElement).render(<App />);