aotoyae

[React] axios.get : HTTP 통신으로 데이터 가져오기 본문

React

[React] axios.get : HTTP 통신으로 데이터 가져오기

aotoyae 2024. 2. 19. 12:01

 

 

💡 Axios : Promise 를 기반으로 해 HTTP 통신을 할 수 있는 라이브러리

 

먼저 npm install axios or yarn add axios ~

npm install json-server or yarn add json-server ~

혹시나 EACCES 에러가 뜬다면 sudo npm install json-server

 

루트 경로에 db.json 파일을 만든다.

{
  "todos": [
    {
      "id": 1,
      "title": "react"
    }
  ]
}

 

그 다음 json-server --watch db.json --port 4000

 

이제 App.jsx 에서 데이터를 가져와보자.

import axios from "axios";
import { useEffect } from "react";

function App() {
  const fetchTodos = async () => {
    const response = await axios.get("http://localhost:4000/todos"); // 가져옵니다.
    console.log(response);
  };

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

  return (
    <div>
      <h1>AXIOS</h1>
    </div>
  );
}

export default App;

 

구조분해할당으로 data 만 가져와보자!

try {
  const { data } = await axios.get("http://localhost:4000/todos");
  console.log(data);
}

 

 

db.js 에 데이터를 더 넣고

App.jsx 에서 가져온 데이터를 useState 로 저장해 화면에 출력해보자.

{
  "todos": [
    {
      "id": 1,
      "title": "react"
    },
    {
      "id": 2,
      "title": "node"
    },
    {
      "id": 3,
      "title": "spring"
    }
  ]
}
import "./App.css";
import axios from "axios";
import { useEffect, useState } from "react";

function App() {
  const [todos, setTodos] = useState(null); // 처음 값은 null

  const fetchTodos = async () => {
    const { data } = await axios.get("http://localhost:4000/todos");
    setTodos(data); // 가져온 데이터 그대로 todos 에 set
  };

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

  return (
    <div>
      <h1>AXIOS</h1>
      {todos.map((todo) => (
        <div key={todo.id}>
          {todo.id} : {todo.title}
        </div>
      ))}
    </div>
  );
}

export default App;

 

 

❗️ 여기서 새로고침을 하면 에러가 뜬다.

화면에 렌더링 되는 return 문이 먼저 실행되고 위의 함수들이 실행되어서

초기 todos 의 값이 비어있는 상태에서 map 을 돌릴 수 없기 때문!

{todos?.map((todo) => (
  <div key={todo.id}>
  {todo.id} : {todo.title}
  </div>
))}

 

todos 에 옵셔널 체이닝을 넣어주면 정상적으로 동작한다!