My Develop Log

[노마드코더]실전형 리액트 Hooks 10개 - (useAxios) 본문

React 공부/노마드코더 노트정리

[노마드코더]실전형 리액트 Hooks 10개 - (useAxios)

Developer_Sammy 2023. 2. 18. 12:15
Axios

Axios란?

Axios는 브라우저, Node.js를 위한 promise API를 활용하는 HTTP 비동기 통신 라이브러리이다.

useAxios

useAxios는 json url prop인 opts와 어떤 형식의 props를 가져올지 설정하는 axiosInstance를 인수로 갖는다.

refetch 함수는 한번 가져온 데이터들을 업데이트 시키는데 기존 state에서 loading 부분만 true로 변환시키고, setTrigger을 통해 현재 시각으로 state를 업데이트 후 렌더링한게 된다. 이렇게 되면 trigger의 값이 변동될 때 실행되는 useEffect를 통해 새로운 데이터를 받아오게 된다.

  • 우선, axios를 Add Dependency를 해준 후, useAxios.js라는 파일을 하나 만들어 준다..

  • 그 후, useAxios.js에 defaultAxios를 import 해준 후 useAxios라는 함수를 만들어 나간다.
// useAxios.js

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

// axios는 디폴드 URL을 설정, axios instance를 보내지 않으면 default로 설정
const useAxios = (opts, axiosInstance = defaultAxios) => {
  const [state, setState] = useState({
    loading: true,
    error: null,
    data: null
  });
  const [trigger, setTrigger] = useState(0);

  if (!opts.url) {
    return;
  }
  const refetch = () => {
    setState({
      ...state,
      loading: true
    });
    setTrigger(Date.now());
  };

  // axios는 데이터를 받으면 처리하고 에러가 있을 때는 catch
  useEffect(() => {
    axiosInstance(opts)
      .then((data) => {
        setState({
          ...state,
          loading: false,
          data
        });
      })
      .catch((error) => {
        setState({ ...state, loading: false, error });
      });
  }, [trigger]);
  return { ...state, refetch };
};

export default useAxios;
  • 다음과 같이 json으로 정리된 링크를 통해 useAxios 함수의 인자로 넘겨준다. https://yts.mx/api/v2/list_movies.json
  • Refetch라는 버튼을 클릭하면 로딩되는 동안 "Loading" 이라는 글이 보이며, 앞서 말했듯이 현재 시각으로 state를 업데이트 후 다시 데이터를 불러오게 된다.

json 예시

// App.js

import useAxios from "./useAxios";

const App = () => {
  const { loading, data, error, refetch } = useAxios({
    url: "https://yts.mx/api/v2/list_movies.json"
  });
  console.log(
    `Loading: ${loading}\nError:${error}\n Data: ${JSON.stringify(data)}`
  );
  return (
    <div className="APP" style={{ height: "1000vh" }}>
      <h1>{data && data.status}</h1>
      <h2>{loading && "Loading"}</h2>
      <button onClick={refetch}>Refetch</button>
    </div>
  );
};

export default App;

 

 

프로젝트를 진행하면서 데이터를 불러올 때,  많이 활용될 것 같아서 더 공부해 나가면서 친숙하게 익혀나가야 할 것 같다.

 

Reference

https://nomadcoders.co/react-hooks-introduction/lectures/1601

 

All Courses – 노마드 코더 Nomad Coders

초급부터 고급까지! 니꼬쌤과 함께 풀스택으로 성장하세요!

nomadcoders.co