2. 로그인, 사용자 목록

사용자 목록

export default function UserListPage() {
  const { users, loading, error } = useFetchUsers();

  if (loading) {
    return <p>Loading...</p>;
  }

  if (error) {
    return <p>Error!</p>;
  }

  return (
    <Container>
      <h2>Users</h2>
      <table>
        <thead>
          <tr>
            <th>이름</th>
            <th>이메일</th>
            <th>역할</th>
          </tr>
        </thead>
        <tbody>
          {users.map((user) => (
            <tr key={user.id}>
              <td>{user.name}</td>
              <td>{user.email}</td>
              <td>{user.role}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </Container>
  );
}

useFetchUsers hook

axios를 바로 쓰지 않았듯

swr도 바로 쓰지않고 useFetch 훅으로 한번 감싸준다.

import useFetch from './useFetch';

import { User } from '../types';

export default function useFetchUsers() {
  const { data, error, loading } = useFetch<{
    users: User[];
  }>('/users');

  return {
    users: data?.users ?? [],
    error,
    loading,
  };
}

useFetch

import useSWR from "swr";

import { apiService } from "../services/ApiService";

const API_BASE_URL = process.env.API_BASE_URL || "http://localhost:3000/admin";

export default function useFetch<Data>(path: string) {
  const url = `${API_BASE_URL}${path}`;

  const { data, error, isLoading, mutate } =
    useSWR < Data > (url, apiService.fetcher());

  return {
    data,
    error,
    loading: isLoading,
    mutate,
  };
}

ApiService

fetcher() {
  return async (url: string) => {
    const { data } = await this.instance.get(url);
    return data;
  };
}

swr은 데이터를 자동으로 가져오고 업데이트 할 수 있어서,

개발자가 수동으로 데이터를 가져오거나 업데이트 해야하는 노력을 줄일 수 있다.

데이터를 관리하고 로딩하는 데 있어서 매우 유용한 라이브러리.

Last updated