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