LoginSignup
0
0

More than 1 year has passed since last update.

Reactでreact-queryを利用する。

Posted at

React-Queryとは

react-queryは非同期通信時のデータをフェッチするためのライブラリ。サーバの状態を管理し、API等での非同期通信によるデータをキャッシュできる。

スクリーンショット 2022-05-26 20.56.43.png

ReactーQueryのサンプル実装

成果物の完成イメージ
スクリーンショット 2022-05-26 21.24.29.png

ディレクトリ構成
~/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
App.tsx
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で囲う必要有り。

User.tsx
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;

UseUsers.tsx
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;
types.ts
export type IUser = {
  user_id: string
  name: string
  gender: string
}
db.json(json-serverで実行)
{
    "users":[
        {
            "user_id":123,
            "name":"kkfactory01",
            "gender":"men"
        },
        {
            "user_id":234,
            "name":"kkfactory02",
            "gender":"women"
        }
    ]
}

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0