Open History to see the last commit
1/* eslint-disable jsx-a11y/anchor-is-valid */
2import React from "react";
3import ReactDOM from "react-dom";
4import { QueryClient, QueryClientProvider, useQueryClient } from "react-query";
5import { ReactQueryDevtools } from "react-query/devtools";
6β
7import usePosts from "./hooks/usePosts";
8import usePost from "./hooks/usePost";
9β
10const queryClient = new QueryClient();
11β
12function App() {
13 const [postId, setPostId] = React.useState(-1);
14β
15 return (
16 <QueryClientProvider client={queryClient}>
17 <p>
18 This example is exactly the same as the basic example, but each query
19 has been refactored to be it's own custom hook. This design is the
20 suggested way to use React Query, as it makes it much easier to manage
21 query keys and shared query logic.
22 </p>
23 {postId > -1 ? (
24 <Post postId={postId} setPostId={setPostId} />
25 ) : (
26 <Posts setPostId={setPostId} />
27 )}
28 <ReactQueryDevtools initialIsOpen />
29 </QueryClientProvider>
30 );
31}
32β
33function Posts({ setPostId }) {
34 const queryClient = useQueryClient();
35 const { status, data, error, isFetching } = usePosts();
36β
37 return (
38 <div>
39 <h1>Posts</h1>
40 <div>
41 {status === "loading" ? (
42 "Loading..."
43 ) : status === "error" ? (
44 <span>Error: {error.message}</span>
45 ) : (
46 <>
47 <div>
48 {data.map((post) => (
49 <p key={post.id}>
50 <a
51 onClick={() => setPostId(post.id)}
52 href="#"
53 style={
54 // We can use the queryCache here to show bold links for
55 // ones that are cached
56 queryClient.getQueryData(["post", post.id])
57 ? {
58 fontWeight: "bold",
59 color: "green",
60 }
61 : {}
62 }
63 >
64 {post.title}
65 </a>
66 </p>
67 ))}
68 </div>
69 <div>{isFetching ? "Background Updating..." : " "}</div>
70 </>
71 )}
72 </div>
73 </div>
74 );
75}
76β
77function Post({ postId, setPostId }) {
78 const { status, data, error, isFetching } = usePost(postId);
79β
80 return (
81 <div>
82 <div>
83 <a onClick={() => setPostId(-1)} href="#">
84 Back
85 </a>
86 </div>
87 {!postId || status === "loading" ? (
88 "Loading..."
89 ) : status === "error" ? (
90 <span>Error: {error.message}</span>
91 ) : (
92 <>
93 <h1>{data.title}</h1>
94 <div>
95 <p>{data.body}</p>
96 </div>
97 <div>{isFetching ? "Background Updating..." : " "}</div>
98 </>
99 )}
100 </div>
101 );
102}
103β
104const rootElement = document.getElementById("root");
105ReactDOM.render(<App />, rootElement);