[React다루는기술] 17. React에서 axios와 Custom Hook 사용 예제
in React on React 다루는 기술
React에서 axios와 Custom Hook 사용 예제포스팅이다. [React다루는기술] 카테고리와 해당 포스팅은 리액트를 다루는 기술(개정판)를 보고 부분적인 기록용으로 작성한 예제로 자세한 내용은 책을 사서 보면 된다.
1. axios 예제
리액트에서 axios 를 활용한 예제이다.
$ yarn add axios
import React, { useState } from "react";
import axios from "axios";
const App = () => {
  const [data, setData] = useState(null);
  const onClick = () => {
    axios
      .get("url")
      .then((response) => {
        setData(response.data);
      });
  };
  return (
    <div>
      <div>
        <button onClick={onClick}>불러오기</button>
      </div>
      {data && (
        <textarea
          rows={7}
          value={JSON.stringify(data, null, 2)}
          readOnly={true}
          style=
        />
      )}
    </div>
  );
};
export default App;
2. useEffect 이용한 axios 호출
뉴스 카테고리들을 클릭 했을 경우에 useEffect를 활용한 카테고리에 맞는 뉴스정보를 요청하는 예제이다.
const NewsList = ({ category }) => {
  const [articles, setArticles] = useState(null);
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    //async를 사용하는 함수 따로 선언
    const fetchData = async () => {
      setLoading(true);
      try {
        const query = category === "all" ? "" : `&category=${category}`;
        const response = await axios.get(
          `url`
        );
        setArticles(response.data.articles);
      } catch (e) {
        console.log(e);
      }
      setLoading(false);
    };
    fetchData();
  }, [category]); //useEffect 로 category가 변경될때마다 axios 요청
  if (loading) {
    return <NewsListBlock>대기 중 ...</NewsListBlock>;
  }
  if (!articles) {
    return null;
  }
  return (
    <NewsListBlock>
      {articles.map((article) => (
        <NewsItem key={article.url} article={article} />
      ))}
    </NewsListBlock>
  );
};
export default NewsList;
3. Custom Hook
Custom Hook을 이용한 axios 예제이다.
useCustomPromise.js
import { useState, useEffect } from "react";
export default function useCustomPromise(promiseCreator, deps) {
  const [loading, setLoading] = useState(false);
  const [resolved, setResolved] = useState(null);
  const [error, setError] = useState(null);
  useEffect(() => {
    const process = async () => {
      setLoading(true);
      try {
        const resolved = await promiseCreator();
        setResolved(resolved);
      } catch (e) {
        setError(e);
      }
      setLoading(false);
    };
    process();
  }, deps);
  return [loading, resolved, error];
}
NewsList.js
Custom Hook인 useCustomPromise 를 만들어서 적용한 예제 코드이다.
 리액트 라이브러리들을 볼때 도움이 되는 예제인듯 한다.
//...
import useCustomPromise from "../lib/useCustomPromise";
//...
const NewsList = ({ category }) => {
  const [loading, response, error] = useCustomPromise(() => {
    const query = category === "all" ? "" : `&category=${category}`;
    return axios.get(
      `url`
    );
  }, [category]);
  if (loading) {
    return <NewsListBlock>대기 중 ...</NewsListBlock>;
  }
  //response가 아직 없는 경우
  if (!response) {
    return null;
  }
  //error가 발생시
  if (error) {
    return <NewsListBlock>에러 발생</NewsListBlock>;
  }
  //response 성공시
  const { articles } = response.data;
  return (
    <NewsListBlock>
      {articles.map((article) => (
        <NewsItem key={article.url} article={article} />
      ))}
    </NewsListBlock>
  );
};
export default NewsList;

