fetch() / axios

samuel Jo·2023년 4월 23일
0

API

목록 보기
2/2

fetch api

Fetch API는 Promise를 사용하여 비동기적으로 데이터를 가져오며, Response 객체를 반환. 반면 Axios는 Promise를 사용하여 비동기적으로 데이터를 가져오지만, Response 객체 대신에 JSON 데이터를 반환.

Fetch API는 간단한 GET 요청을 보내는 데는 적합하지만, 헤더와 같은 더 복잡한 요청을 처리하기에는 번거롭다. 반면 Axios는 더 많은 기능을 제공하며, 요청을 처리하기 쉬움.

따라서 Axios는 더 많은 기능과 간단한 사용법으로 Fetch API보다 효율적
그러나 브라우저에서 기본적으로 제공되는 Fetch API를 사용하면 추가 라이브러리를 설치할 필요가 없으므로 프로젝트 규모에 따라 선택.

~~~
export const Popular = () => {

  const [popular, SetPopular] = useState([]);

  useEffect(() => {
    getPopular();
  }, []);


  const getPopular = async () => {
    const check = localStorage.getItem("popular");

    if (check) {
      SetPopular(JSON.parse(check));
    } else {
      const api = await fetch(
        `https://api.spoonacular.com/recipes/random?apiKey=${process.env.REACT_APP_API_KEY}&number=9`
      );
      const data = await api.json();

      localStorage.setItem("popular", JSON.stringify(data.recipes))
      SetPopular(data.recipes);
      console.log(data.recipes)
    }





  };
  
 return(
     ~~~
 );

이렇게 fetch를 사용해도 되고,

// npm i axios 후,

import axios from 'axios';

const getPopular = async () => {
  const check = localStorage.getItem("popular");

  if (check) {
    SetPopular(JSON.parse(check));
  } else {
    try {
      const response = await axios.get(`https://api.spoonacular.com/recipes/random?apiKey=${process.env.REACT_APP_API_KEY}&number=9`);
      const data = response.data;
      
      localStorage.setItem("popular", JSON.stringify(data.recipes))
      SetPopular(data.recipes);
      console.log(data.recipes)
    } catch (error) {
      console.error(error);
    }
  }
};

이런식으로 사용해도 된다.

profile
step by step

0개의 댓글