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

index.js

106 lines2.6 KB

1/* eslint-disable jsx-a11y/anchor-is-valid */
2import React from "react";
3import ReactDOM from "react-dom";
4import axios from "axios";
5import { useQuery } from "react-query";
6​
7const getPosts = async () => {
8 const { data } = await axios.get(
9 "https://jsonplaceholder.typicode.com/posts"
10 );
11 return data;
12};
13​
14const getPostById = async (key, id) => {
15 const { data } = await axios.get(
16 `https://jsonplaceholder.typicode.com/posts/${id}`
17 );
18 return data;
19};
20​
21function App() {
22 const [postId, setPostId] = React.useState(-1);
23​
24 return (
25 <>
26 <p>
27 As you visit the posts below, you will notice them in a loading state
28 the first time you load them. However, after you return to this list and
29 click on any posts you have already visited again, you will see them
30 load instantly and background refresh right before your eyes!{" "}
31 <strong>
32 (You may need to throttle your network speed to simulate longer
33 loading sequences)
34 </strong>
35 </p>
36 {postId > -1 ? (
37 <Post postId={postId} setPostId={setPostId} />
38 ) : (
39 <Posts setPostId={setPostId} />
40 )}
41 </>
42 );
44​
45function Posts({ setPostId }) {
46 const { status, data, error, isFetching } = useQuery("posts", getPosts);
47​
48 return (
49 <div>
50 <h1>Posts</h1>
51 <div>
52 {status === "loading" ? (
53 "Loading..."
54 ) : status === "error" ? (
55 <span>Error: {error.message}</span>
56 ) : (
57 <>
58 <div>
59 {data.map(post => (
60 <p key={post.id}>
61 <a onClick={() => setPostId(post.id)} href="#">
62 {post.title}
63 </a>
64 </p>
65 ))}
66 </div>
67 <div>{isFetching ? "Background Updating..." : " "}</div>
68 </>
69 )}
70 </div>
71 </div>
72 );
74​
75function Post({ postId, setPostId }) {
76 const { status, data, error, isFetching } = useQuery(
77 postId && ["post", postId],
78 getPostById
79 );
80​
81 return (
82 <div>
83 <div>
84 <a onClick={() => setPostId(-1)} href="#">
85 Back
86 </a>
87 </div>
88 {!postId || status === "loading" ? (
89 "Loading..."
90 ) : status === "error" ? (
91 <span>Error: {error.message}</span>
92 ) : (
93 <>
94 <h1>{data.title}</h1>
95 <div>
96 <p>{data.body}</p>
97 </div>
98 <div>{isFetching ? "Background Updating..." : " "}</div>
99 </>
100 )}
101 </div>
102 );
104​
105const rootElement = document.getElementById("root");
106ReactDOM.render(<App />, rootElement);