1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Reactについて学んだことをまとめる(その6)

Posted at

以下のUdemyの講座を受講したので、学んだことをまとめていく。

カスタムフック

ロジック部分をカスタムフックとして切り出しておくと使いまわしやテストが楽になる。
カスタムフックは通常の関数とほぼ同じだが、以下の点が異なる。

  • 関数名をuseから始める
  • 返り値はオブジェクトで必要な関数・Stateを全て包んで返すか、useStateなど他のフックの返り値の形式に合わせる

カスタムフックの例

useAllUsers.ts
//全ユーザー一覧を取得するカスタムフック

import { useState } from 'react';
import { UserProfile } from '../types/UserProfile';
import axios from 'axios';
import { User } from '../types/api/User';

export const useAllUsers = () => {
  const [userProfiles, setUserProfiles] = useState<Array<UserProfile>>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<boolean>(false);

  const getUsers = () => {
    setLoading(true);
    setError(false);
    axios
      .get<Array<User>>('https://jsonplaceholder.typicode.com/users')
      .then((res) => {
        const data = res.data.map((user) => ({
          id: user.id,
          name: `${user.name}(${user.username})`,
          email: user.email,
          address: `${user.address.city}${user.address.suite}${user.address.street}`,
        }));
        setUserProfiles(data);
      })
      .catch(() => {
        setError(true);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  return { getUsers, userProfiles, loading, error };
};
App.tsx
import { UserCard } from './components/UserCard';
import { useAllUsers } from './hooks/useAllUsers';

function App() {
  const { getUsers, userProfiles, loading, error } = useAllUsers();
  const onClickFetchUser = () => getUsers();
  return (
    <>
      <div>
        <button onClick={onClickFetchUser}>データ取得</button>
        <br />
        {error ? (
          <p style={{ color: 'red' }}>データの取得に失敗しました</p>
        ) : loading ? (
          <p>Loading...</p>
        ) : (
          <>
            {userProfiles.map((user) => (
              <UserCard key={user.id} user={user} />
            ))}
          </>
        )}
      </div>
    </>
  );
}

export default App;
1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?