使用React中的react-query库
React-Query是什么?
react-query是用于获取异步通信数据的库。它可以管理服务器状态并通过API等进行异步通信的数据缓存。
React-Query的示例实现
~/develop/react/react-query-tutorial $ tree src
src
├── App.css
├── App.tsx
├── UseUsers.tsx ←react-queryの本実装
├── User.tsx
├── index.css
├── index.tsx
├── logo.svg
├── react-app-env.d.ts
├── reportWebVitals.ts
├── setupTests.ts
└── types.ts
0 directories, 11 files
import { QueryClient, QueryClientProvider } from "react-query";
import Users from "./User";
import "./App.css";
const QUERY_CLIENT = new QueryClient();
function App() {
return (
<QueryClientProvider client={QUERY_CLIENT}>
<div className="app">
<h1 className="title white">ユーザ一覧</h1>
<Users />
</div>
</QueryClientProvider>
);
}
export default App;
如果使用react-query,需要在QueryClientProvider中进行包装。
import useUsers from "./UseUsers";
import "./App.css";
const Users: React.FC = () => {
const { isLoading, users } = useUsers();
// Loading状態を検知する
if (isLoading) {
return <div className="loading">is loading...</div>;
}
return (
<div>
{!!users?.length &&
users.map((user) => (
<p key={user.name} className="user_name">
{user.name}
</p>
))}
</div>
);
};
export default Users;
import { useQuery } from "react-query";
import { IUser } from "./types";
const API_URL = "http://localhost:3030/users";
const useUsers = () => {
const {
data: users, // 実際の取得データ
isLoading, // 取得中であるかどうかを検知する。
error,
} = useQuery<IUser[]>("users", () =>
fetch(API_URL).then((res) => res.json())
);
return { users, isLoading, error };
};
export default useUsers;
export type IUser = {
user_id: string
name: string
gender: string
}
{
"users":[
{
"user_id":123,
"name":"kkfactory01",
"gender":"men"
},
{
"user_id":234,
"name":"kkfactory02",
"gender":"women"
}
]
}
请看这个