반응형
Notice
Recent Posts
Recent Comments
Link
관리 메뉴

짧은코딩

React에서 API 호출하기 본문

인프런, 유데미/한입 크기로 잘라 먹는 리액트

React에서 API 호출하기

5_hyun 2022. 5. 26. 20:11
반응형

-API 호출을 위한 사이트

https://jsonplaceholder.typicode.com/

 

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

 

여기에는 어떤 API 서비스로 자원을 가져다가 쓸 수 있는지 리스팅을 해놨다. 이중에서 comments를 사용했다.

 

comments의 내용에서 이런 것을 활용해 데이터를 가공했다.

 

-App.js

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

//https://jsonplaceholder.typicode.com/comments

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(),
        id: dataId.current++,
      };
    });

    setData(initData);
  };

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

  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;

 

-수정한 부분

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(),
        id: dataId.current++,
      };
    });

    setData(initData);
  };

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

API에서 불러와서 일기에 사용한다.

컴포넌트 마운트 시점에 getData라는 함수를 만들어서 async와 await을 사용해 데이터를 가공하여 일기의 기본값을 만들어봤다.

반응형

'인프런, 유데미 > 한입 크기로 잘라 먹는 리액트' 카테고리의 다른 글

최적화 1 - useMemo  (0) 2022.05.27
React developer tools  (0) 2022.05.27
Lifecycle 제어하기  (0) 2022.05.26
데이터 수정하기  (0) 2022.05.25
데이터 삭제하기  (0) 2022.05.25
Comments