FrontEngineer JungBam

Custom Hook 2차 시도 : useAxios 본문

리액트

Custom Hook 2차 시도 : useAxios

정밤톨 2022. 12. 12. 09:19
import React, { useState } from "react";
import axios from "axios";
import { useDispatch } from "react-redux";
import { initialTodos } from "../../../redux/modules/postSlice";

const instance = axios.create({
  baseURL: "http://localhost:3001",
  headers: { "X-Custom-Header": "foobar" },
  timeout: 1000,
});

export const useAxios = (url) => {
  const [error, setError] = useState(false);
  const [isLoading, setLoading] = useState(false);
  const dispatch = useDispatch();

  const getData = async () => {
    setLoading(true);
    setError(false);
    try {
      const { data } = await instance.get(`/${url}`);
      setLoading(false);
      dispatch(initialTodos(data));
    } catch (error) {
      setLoading(false);
      setError(true);
    }
  };

  return { error, isLoading, getData };
};

 

useEffect Hook을 axios 버전으로 만들어 봤다. axios를 통해 초반에 데이터를 get해오는 로직.
여기서 조금 더 올리면 data 자체를 가공해서 컴포넌트로 만들어서 return 시키는 방법까지 구현하면 유연성은 떨어지지만 하나의 테마 프로젝트 안에서의 활용은 올라갈 것이라는 생각이 든다.

반응형

'리액트' 카테고리의 다른 글

react-beautiful-dnd(선택 이유)  (0) 2023.01.26
CustomHooks 3차 시도 : useValidation  (0) 2022.12.15
redux-toolkit  (0) 2022.12.08
Custom Hooks 1차 시도 : useHttp  (0) 2022.12.07
useEffect에서 함수를 동작시킬 때  (0) 2022.12.07
Comments