본문 바로가기

React

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

DELETE 요청

 

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

function App() {
  const [todos, setTodos] = useState(null);
  const [inputValue, setInputValue] = useState({
    title: "", // title 을 입력하는 것 이므로 title 값을 넣어줌.
  });

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

  const onSubmitHandler = async () => {
    // 무슨 값을 post 로 보낼 것인가에 대한 async, 여기서는 값을 따로 가져오는게 아니므로 없어도 무방
    axios.post(`http://localhost:4000/todos`, inputValue);
    setTodos([...todos, inputValue]); // 값 추가
  };

  const onDeleteHandler = async (id) => {
    // 무슨 값을 delete 할건지에 대한 async
    axios.delete(`http://localhost:4000/todos/${id}`);
    setTodos(todos.filter((todo) => todo.id !== id));
  };

  useEffect(() => {
    // 마운트 되었을 때 실행할 로직, db로부터 값을 가져올 것이다.
    fetchTodos();
    return () => {
      // 언마운트 되었을 때 리턴할 값
    };
  }, []); // 어떤 state 가 변경될 때, 실행하는지 결정
  return (
    <>
      <div>
        <h1>인풋 영역</h1>
        <form
          onSubmit={(e) => {
            e.preventDefault();
            onSubmitHandler();
          }}
        >
          <input
            type="text"
            value={inputValue.title}
            onChange={(e) =>
              setInputValue({
                title: e.target.value,
              })
            }
          />
          <button type="submit">추가</button>
        </form>
      </div>
      <div>
        <h1>데이터 영역</h1>
        {todos?.map((todo) => {
          return (
            <div id={todo.id}>
              {todo.id} : {todo.title}
              &nbsp;
              <button onClick={() => onDeleteHandler(todo.id)}>삭제</button>
              {/* 콜백함수로 작성해야 렌더링 하고 함수 호출. */}
            </div>
          );
        })}
      </div>
    </>
  );
}

export default App;

'React' 카테고리의 다른 글

[React] Fetch 와 Axios  (0) 2023.07.04
[React] 비동기 통신 axios(patch)  (0) 2023.07.04
[React] 비동기 통신 axios(post)  (0) 2023.07.04
[React] 비동기 통신 axios(get)  (0) 2023.07.04
[React] HTTP  (0) 2023.07.04