Java Scripts/React.js

Hook in React - useAxios

HobbyCoding 2023. 9. 28. 13:39
728x90

note)  console.log(`loading:${loading}\nError:${error}\nData:${JSON.stringify(data)}`)  
변수를 ${} 을 이용하여 여러 data 를 하나의 string 으로 표시하는 기술이다 ( awesome )

 

note) return { ...state, refetch }; 와 같이 return 되는 것을  const {loading, data, error, refetch} = useAxios({url: "https://yts.mx/api/v2/list_movies.json"}); 와 같이 원허눈 것을 지정하여 받을 수도 있다.

 

note) settrigger 를  이용하여 trigger 를 강제로 변경 시켜,  useEffect 를 실행하는 구조로 되어 있다.

 

note) below has fully working project

https://github.com/pidokige02/hooks_prac

 

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

export 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());
  };
  useEffect(() => {
    axiosInstance(opts)
      .then(data => {
        setState({
          ...state,
          loading: false,
          data
        });
      })
      .catch(error => {
        setState({ ...state, loading: false, error });
      });
  }, [trigger]);
  return { ...state, refetch };
};

 

 

note) 위는 아래의 교육과장을 이수하면서 정리한 것이다.

https://nomadcoders.co/react-hooks-introduction/lobby?utm_source=free_course&utm_campaign=react-hooks-introduction&utm_medium=site