본문 바로가기

React

[React] 비동기 통신 axios(get)

 

GET 요청

 

db.json에 저장한 값을 port 4000 을 통해 가져옴

function App() {
  const fetchTodos = async () => {
    // 서버로부터 값 요청, 비동기
    const { data } = await axios.get("http://localhost:4000/todos"); // 서버로부터 값을 받을때 까지 기다림
    console.log("data", data);
  };

  useEffect(() => {
    // 마운트 되었을 때 실행할 로직, db로부터 값을 가져올 것이다.
    fetchTodos();
    return () => {
      // 언마운트 되었을 때 리턴할 값
    };
  }, []); // 어떤 state 가 변경될 때, 실행하는지 결정
  return <div>Axios</div>;
}

 

 

또한 가져온 값을 이용해서 화면에 뿌려줄 수 있음.

 

import axios from "axios";
import "./App.css";
import { useEffect } from "react";
import { useState } from "react";

function App() {
  const [todos, setTodos] = useState(null);

  const fetchTodos = async () => {
    // 서버로부터 값 요청, 비동기
    const { data } = await axios.get("http://localhost:4000/todos"); // 서버로부터 값을 받을때 까지 기다림
    console.log("data", data);
    setTodos(data); // todos 를 이용해 값을 뿌려줄 수 있음.
  };

  useEffect(() => {
    // 마운트 되었을 때 실행할 로직, db로부터 값을 가져올 것이다.
    fetchTodos();
    return () => {
      // 언마운트 되었을 때 리턴할 값
    };
  }, []); // 어떤 state 가 변경될 때, 실행하는지 결정
  return (
    <div>
      {todos.map((todo) => {
        return (
          <div key={todo.id}>
            {todo.id} : {todo.title}
          </div>
        );
      })}
    </div>
  );
}

export default App;

 

나는 오류가 나지 않았지만 todos.map 이 data 를 불러오기 전에 실행 된다면 null 이 되기 때문에, 옵셔널 체이닝을 통해 다음과 같이

todos?.map 으로 작성해주면 오류를 해결할 수 있음.

return (
    <div>
      {todos?.map((todo) => { // 옵셔널체이닝
        return (
          <div id={todo.id}>
            {todo.id} : {todo.title}
          </div>
        );
      })}
    </div>
  );

 

'React' 카테고리의 다른 글

[React] 비동기 통신 axios(delete)  (0) 2023.07.04
[React] 비동기 통신 axios(post)  (0) 2023.07.04
[React] HTTP  (0) 2023.07.04
[React] json-server  (0) 2023.07.04
[React] Redux toolkit/ Devtools/ Flux 패턴  (0) 2023.07.04