타입스크립트에서 커스텀훅을 이용해 axios로 데이터 받아오기

Kyungoh Kang·2021년 1월 31일
2

타입스크립트에서 커스텀훅을 이용해 axios로 데이터 받아오기

interface IgetData {
  url: string;
}

interface IResponse {
  id: number;
  first_name: string;
  last_name: string;
  email: string;
  gender: string;
}

export const getData = (url: IgetData) => {
  const [response, setResponse] = useState<IResponse[]>();
  const [error, setError] = useState<string>("");
  const [isLoading, setIsLoading] = useState<boolean>(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        axios(url)
          .then((res) => {
            setResponse(res.data);
          })
          .finally(() => {
            setIsLoading(false);
          });
      } catch (err) {
        setError(err);
      }
    };
    if (isLoading) {
      fetchData();
    }
  }, [url]);

  return { response, error, isLoading };
};

사용 코드

import React from "react";
import { getData } from "~/Hooks";

export const Modal: React.FC = () => {
  const { response, error, isLoading } = getData({
    url: "/mockdata/MOCK_DATA.json",
  });
  if (isLoading) {
    return null;
  }
  if (response) {
    console.log(response);
  }

  console.log(response?.map((el) => el.first_name));

  return <div></div>;
};
///Modal 컴포넌트에서 임포트해와서 데이터 받아와서 맵돌리기

후기

커스텀훅을 이용해 데이터를 받아오면 url만 바꿔 훅의 인자로 넘겨주면 여러 주소에서 다른 데이터를 받아올 수 있기 때문에 데이터를 받아오는 함수를 여러번 작성해야 하는 상황에서 활용할 수 있을 것 같다.
데이터를 받아오는 것 뿐만 아니라 서로 다른 컴포넌트에서 같은 기능이 필요하다면 커스텀훅을 이용해 기능을 구현해 활용할수 있을듯.
ui컴포넌트들을 재사용하듯이 함수를 재사용한다는 느낌으로 커스텀훅을 사용할 수 있을 것 같다. 익숙해지려면 다양한 훅을 만들어보는 것이 좋겠다.

0개의 댓글