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 axios from "axios";
5import {
6 Link,
7 MakeGenerics,
8 MatchRoute,
9 Outlet,
10 ReactLocation,
11 Router,
12 useLoadRoute,
13 useMatch,
14} from "@tanstack/react-location";
15import {
16 useQuery,
17 useQueryClient,
18 QueryClient,
19 QueryClientProvider,
20} from "react-query";
21import { ReactQueryDevtools } from "react-query/devtools";
22β
23//
24β
25type Post = {
26 id: string;
27 title: string;
28 body: string;
29};
30β
31type LocationGenerics = MakeGenerics<{
32 Params: { postId: string };
33}>;
34β
35//
36β
37const location = new ReactLocation<LocationGenerics>();
38const queryClient = new QueryClient();
39β
40function App() {
41 return (
42 <QueryClientProvider client={queryClient}>
43 <Router
44 location={location}
45 routes={[
46 {
47 path: "/",
48 element: "Welcome Home!",
49 },
50 {
51 path: "posts",
52 element: <Posts />,
53 loader: () =>
54 queryClient.getQueryData("posts") ??
55 queryClient.fetchQuery("posts", fetchPosts).then(() => ({})),
56 children: [
57 { path: "/", element: "Select a post." },
58 {
59 path: ":postId",
60 element: <Post />,
61 loader: ({ params: { postId } }) =>
62 queryClient.getQueryData(["posts", postId]) ??
63 queryClient.fetchQuery(["posts", postId], () =>
64 fetchPostById(postId)
65 ),
66 },
67 ],
68 },
69 ]}
70 >
71 <div>
72 <h1>Basic With React Query</h1>
73 <hr />
74 <h3>
75 <Link to=".">Home</Link>{" "}
76 <Link to="posts" preload={1}>
77 Posts
78 </Link>
79 </h3>
80 <Outlet />
81 </div>
82 </Router>
83 <ReactQueryDevtools initialIsOpen />
84 </QueryClientProvider>
85 );
86}
87β
88async function fetchPosts() {
89 await new Promise((r) => setTimeout(r, 500));
90 const { data } = await axios.get(
91 "https://jsonplaceholder.typicode.com/posts"
92 );
93 return data;
94}
95β
96function usePosts() {
97 return useQuery<Post[], any>("posts", fetchPosts);
98}
99β
100function Posts() {
101 const queryClient = useQueryClient();
102 const { status, data, error, isFetching } = usePosts();
103 const loadRoute = useLoadRoute();
104β
105 return (
106 <div>
107 <h2>Posts {isFetching ? "..." : ""}</h2>
108 <div>
109 {status === "loading" ? (
110 "Loading..."
111 ) : status === "error" ? (
112 <span>Error: {error.message}</span>
113 ) : (
114 <>
115 <div style={{ display: "flex", flexWrap: "wrap" }}>
116 <div style={{ flex: "0 0 200px" }}>
117 {data?.map((post) => (
118 <p key={post.id}>
119 <Link
120 to={`./${post.id}`}
121 onMouseEnter={() => loadRoute({ to: post.id })}
122 style={
123 // We can access the query data here to show bold links for
124 // ones that are cached
125 queryClient.getQueryData(["posts", `${post.id}`])
126 ? {
127 fontWeight: "bold",
128 color: "green",
129 }
130 : {}
131 }
132 >
133 {post.title}{" "}
134 <MatchRoute to={post.id} pending>
135 ...
136 </MatchRoute>
137 </Link>
138 </p>
139 ))}
140 </div>
141 <div style={{ flex: "1 1" }}>
142 <Outlet />
143 </div>
144 </div>
145 </>
146 )}
147 </div>
148 </div>
149 );
150}
151β
152const fetchPostById = async (id: string) => {
153 await new Promise((r) => setTimeout(r, 500));
154 const { data } = await axios.get(
155 `https://jsonplaceholder.typicode.com/posts/${id}`
156 );
157 return data;
158};
159β
160function usePost(postId: string) {
161 return useQuery<Post, any>(["posts", postId], () => fetchPostById(postId), {
162 enabled: !!postId,
163 });
164}
165β
166function Post() {
167 const {
168 params: { postId },
169 } = useMatch();
170β
171 const { status, data, error, isFetching } = usePost(postId);
172β
173 return (
174 <div>
175 <div>
176 <Link to="..">Back</Link>
177 </div>
178 {!postId || status === "loading" ? (
179 "Loading..."
180 ) : status === "error" ? (
181 <span>Error: {error.message}</span>
182 ) : (
183 <>
184 <h1>
185 {data?.title} {isFetching ? "..." : " "}
186 </h1>
187 <div>
188 <p>{data?.body}</p>
189 </div>
190 </>
191 )}
192 </div>
193 );
194}
195β
196const rootElement = document.getElementById("root");
197ReactDOM.render(<App />, rootElement);