세현's 개발로그

[React] React에서 API 호출하기 본문

React

[React] React에서 API 호출하기

SarahPark 2023. 5. 6. 14:27

◈ API 호출하기

useEffect를 이용하여 컴포넌트의 Mount 시점에 API를 호출해보자.

App.js

1) const getData = async () => {
    const res = await fetch(
      "https://jsonplaceholder.typicode.com/comments"
    ).then((res) => res.json());

 

async/await을 이용하여 getData가 promise를 반환하는 비동기 함수를 만들어주었다.

fetch에 API의 URL을 넣어주고, then을 이용하여 결과를 json 형식으로 받아주었다.

consol.log(res);를 해보면 데이터가 잘 전달되었음을 확인할 수 있다.

2)   const initData = res.slice(0, 20).map((it) => {
      return {
        author: it.email,
        content: it.body,
        emotion: Math.floor(Math.random() * 5) + 1,
        created_date: new Date().getTime() + 1,
        id: dataId.current++
      };
    });

    setData(initData);
  };

 

500개의 API 정보에서 20개까지만 사용하고, map을 이용하여 필요한 정보만 골라주었다.

감정 점수는 random을 이용하여 1~5의 난수를 생성하고 floor를 이용하여 정수로 바꿔줬다. 

initData를 setData에 넣어주어 일기리스트의 상태를 바꿔줬다.

 

3)  useEffect(() => {
    setTimeout(() => {
      getData();
    }, 1500);
  }, []);

 

App.js컴포넌트가 Mount 되자마자 getData를 호출해주기 위해, 빈 배열을 전달해준다.

import { useEffect, useRef, useState } from "react";
import "./App.css";
import DiaryEditor from "./DiaryEditor";
import DiaryList from "./DiaryList";

const App = () => {
  const [data, setData] = useState([]);
  const dataId = useRef(0);

  const getData = async () => {
    const res = await fetch(
      "https://jsonplaceholder.typicode.com/comments"
    ).then((res) => res.json());

    const initData = res.slice(0, 20).map((it) => {
      return {
        author: it.email,
        content: it.body,
        emotion: Math.floor(Math.random() * 5) + 1,
        created_date: new Date().getTime() + 1,
        id: dataId.current++
      };
    });

    setData(initData);
  };

  useEffect(() => {
    setTimeout(() => {
      getData();
    }, 1500);
  }, []);

  const onCreate = (author, content, emotion) => {
    const created_date = new Date().getTime();
    const newItem = {
      author,
      content,
      emotion,
      created_date,
      id: dataId.current
    };
    dataId.current += 1;
    setData([newItem, ...data]);
  };

  const onRemove = (targetId) => {
    const newDiaryList = data.filter((it) => it.id !== targetId);
    setData(newDiaryList);
  };

  const onEdit = (targetId, newContent) => {
    setData(
      data.map((it) =>
        it.id === targetId ? { ...it, content: newContent } : it
      )
    );
  };

  return (
    <div className="App">
      <DiaryEditor onCreate={onCreate} />
      <DiaryList onEdit={onEdit} onRemove={onRemove} diaryList={data} />
    </div>
  );
};
export default App;

 

데이터터가 전달된 모습

Comments