솔로 프로젝트 - fetch custom hooks으로 변환

챔수·2023년 5월 23일
0

개발 공부

목록 보기
66/101

저번시간에 배운 custom hooks를 이용해 fetch API를 커스텀훅으로 변환하는 작업을 하였다.

function App() {
  const [maindata, setMaindate] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    setIsLoading(true);
    axios("http://cozshopping.codestates-seb.link/api/v1/products").then(
      (res) => {
        setMaindate(res.data);
        setIsLoading(false);
      }
    );
  }, []);
  
  (생략)
}

App.js에서 불러오고 있는 fetci API를 커스텀 훅으로 바꾸는 작업을 진행했다. 처음으로 src폴더 내부에 hooks폴더를 만들어 useFetch.js파일을 만들어 주었다.

그 후 훅 내부로 들어가야 할 내용들을 넣어 주었다.

function useFetch() {
  const [maindata, setMaindate] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    setIsLoading(true);
    axios("http://cozshopping.codestates-seb.link/api/v1/products").then(
      (res) => {
        setMaindate(res.data);
        setIsLoading(false);
      }
    );
  }, []);
}

export default useFetch;

react기본 훅으로 사용된 useState와 useEffect, axios라이브러리도 불러줬다.

import { useState, useEffect } from "react";
import axios from "axios";

function useFetch() {
  const [maindata, setMaindate] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    setIsLoading(true);
    axios("http://cozshopping.codestates-seb.link/api/v1/products").then(
      (res) => {
        setMaindate(res.data);
        setIsLoading(false);
      }
    );
  }, []);
}

export default useFetch;

그 후 인자로 url값을 받을 것이기 때문에 매개변수로 url을 넣어주고 사용해야 하는 부분과 의존성배열 부분에 url을 넣어준다. 그리고 훅을 만들때는 함수이기 때문에 내가 원하는 값의 리턴을 필수로 해줘야 한다. 프로젝트에서 필요한 부분은 maindata에 들어간 API정보들과 isLoading에 들어간 boolean값을 리턴 해주었다.

import { useState, useEffect } from "react";
import axios from "axios";

function useFetch(url) {
  const [maindata, setMaindate] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    setIsLoading(true);
    axios(url).then((res) => {
      setMaindate(res.data);
      setIsLoading(false);
    });
  }, [url]);

  return [maindata, isLoading];
}

export default useFetch;

마지막으로 만들어준 훅을 사용하고싶은 곳에서 넣어준다.

function App() {
  const [maindata, isLoading] = useFetch(
    "http://cozshopping.codestates-seb.link/api/v1/products"
  );
  
  (생략)
}

길었던 코드들이 하나의 훅으로 만들어 줘서 보기에도 편하고 만약 수정사항이나 관련 에거가 생겼을때 다른 여러 컨포넌트들을 확인해야되는것이 아닌 커스텀 훅만 확인해보면 되기 때문에 유지 보수도 쉬워질듯 하다.

빈 배열이었을 경우 isLoadingture, 값이 잘 들어왔다면 false값이 잘 들어오는것을 볼 수 있다.

profile
프론트앤드 공부중인 챔수입니다.

0개의 댓글