Dorothy_YANG
With Dorothy
Dorothy_YANG
전체 방문자
오늘
어제
  • 분류 전체보기 (279)
    • Hi, I'm Dorothy 🕵️‍♂️ (21)
      • Slowly but Surely (18)
      • IT certifications (3)
    • 🤯TIL (80)
      • HTML & CSS (2)
      • Javascript & jQuery (13)
      • React (13)
      • C언어 (1)
      • JAVA (22)
      • Python (2)
      • Oracle SQL (10)
      • My SQL (5)
      • Spring (12)
    • 💻Programmers (17)
    • 🏫 Open API_JAVA (101)
    • 🌎 Project (10)
      • Shopping (10)
    • 💥 Error (24)
    • ⚙ Setting (23)

블로그 메뉴

  • 홈
  • 방명록

공지사항

인기 글

태그

  • 오류해결
  • 백준
  • 기간쿼리
  • 서버등록
  • HTML
  • SQLD합격
  • SQL
  • 파이썬온라인
  • Javascript
  • 창초기화
  • 연습문제
  • 콜라보레이토리
  • 코딩앙마
  • Eclipse
  • 비쥬얼스튜디오코드
  • 이것이자바다
  • Database
  • java
  • 독학후기
  • AllArgsConstructor
  • 시작일종료일
  • 노마드코더
  • spring
  • 기간설정
  • SQLD합격후기
  • oracle
  • CSS
  • colaboratory
  • googlecolaboratory
  • sql기간

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Dorothy_YANG

With Dorothy

🤯TIL/React

[한입 크기로 잘라 먹는 리액트] React에서 API 호출하기

2023. 11. 19. 19:28
728x90

 

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. Serving ~2 billion requests each month.

jsonplaceholder.typicode.com

 

https://jsonplaceholder.typicode.com/comments

 

 

App.js

- API 호출 코드 getData작성

- mount될 때 나와야 하는 데이터 > useEffect 사용(빈배열)

- 초기 데이터 initData 설정

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

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

function 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());
    console.log(res);

    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) => {
    console.log(`${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 onRemove={onRemove} diaryList={data} onEdit={onEdit} />
    </div>
  );
}

export default App;

 

 

 

 

 

 


  • 출처
    https://inf.run/N9fZn
 

한입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지 - 인프런 | 강의

개념부터 독특한 프로젝트까지 함께 다뤄보며 자바스크립트와 리액트를 이 강의로 한 번에 끝내요. 학습은 짧게, 응용은 길게 17시간 분량의 All-in-one 강의!, 리액트, 한 강의로 끝장낼 수 있어요.

www.inflearn.com

 

728x90
저작자표시 비영리 변경금지 (새창열림)

'🤯TIL > React' 카테고리의 다른 글

[React] async와 await를 사용한 CRUD  (0) 2023.11.30
[한입 크기로 잘라 먹는 리액트] simpleDiary 코드  (1) 2023.11.19
[한입 크기로 잘라 먹는 리액트] React Lifecycle 제어하기 - useEffect  (1) 2023.11.19
[한입 크기로 잘라 먹는 리액트] React에서 배열 사용하기 4 - 데이터 수정하기  (1) 2023.11.19
[한입 크기로 잘라 먹는 리액트] React에서 배열 사용하기 3 - 데이터 삭제하기  (0) 2023.11.19
    '🤯TIL/React' 카테고리의 다른 글
    • [React] async와 await를 사용한 CRUD
    • [한입 크기로 잘라 먹는 리액트] simpleDiary 코드
    • [한입 크기로 잘라 먹는 리액트] React Lifecycle 제어하기 - useEffect
    • [한입 크기로 잘라 먹는 리액트] React에서 배열 사용하기 4 - 데이터 수정하기
    Dorothy_YANG
    Dorothy_YANG
    Slowly but Surely, 비전공 문과생의 개발공부

    티스토리툴바