[React] API 호출하기

2022. 8. 4. 14:38React

1. jsonplaceholer

 

JSONPlaceholder - Free Fake REST API

{JSON} Placeholder Free fake API for testing and prototyping. Powered by JSON Server + LowDB. Tested with XV. As of Oct 2021, serving ~1.7 billion requests each month.

jsonplaceholder.typicode.com

comments 를 클릭해 JSON 확인하기

 

 

2.App.js

  const getDate = async () => {
    const res = await fetch('https://jsonplaceholder.typicode.com/comments')
      .then((res) => res.json());
      
    const initData = res.slice(0, 20).map((item) => {
      return {
        author: item.email,
        content: item.body,
        emotion: Math.floor(Math.random() * 5) + 1,
        created_date: new Date().getTime(),
        id: dataId.current++
      }
    })
    
     setData(initData)
  }
  
  // mount 될 때 API 호출
  useEffect(() => {
    getDate()
  }, [])

Math.floor() : 주어진 숫자와 같거나 작은 정수 중에서 가장 큰 수를 반환

Math.random() : 위의 코드에선 0.xxx ~ 4.xxx 랜덤으로 나옴

즉,emotion은  1-5까지 랜덤으로 숫자가 나오는 코드임

 

 

 

3. App.js 최종코드

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

function App() {
  // 일기가 없는 상태니깐 빈 배열로 출발!
  const [data, setData] = useState([]);
  const dataId = useRef(0);

  const getDate = async () => {
    const res = await fetch('https://jsonplaceholder.typicode.com/comments')
      .then((res) => res.json());
    const initData = res.slice(0, 20).map((item) => {
      return {
        author: item.email,
        content: item.body,
        emotion: Math.floor(Math.random() * 5) + 1,
        created_date: new Date().getTime(),
        id: dataId.current++
      }
    });
    setData(initData)
  }

  useEffect(() => {
    // API 호출
    getDate();
  }, [])

  // 새로운 일기를 추가하는 함수
  const onCreate = (author, content, emotion) => {
    const created_date = new Date().getTime()
    const newItem = {author, content, emotion, created_date, id: dataId.current };
    dataId.current += 1;
    // 새 일기를 쓸 때 마다 맨위로 오게하기 위해, newItem을 먼저 씀!
    setData([newItem, ...data])
  }

  // 삭제하기
  const onRemove = (targetId) => {
    const newDiaryList = data.filter((item) => item.id !== targetId)
    setData(newDiaryList)
  }

  // 수정하기
  const onEdit = (targetId, newContent) => {
    setData(data.map((item) =>
      item.id === targetId ? {...data, content: newContent} : item
    ))
  }

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

export default App;
mount시점에 API 호출하는 getData 함수를 만들어서 
자바스크립트 내장객체 fetch와 async await키워드를 이용해서 
데이터 가공 후, 일기 데이터의 초깃값을 설정해 봄.

 

 

 

 

방법2