본문 바로가기

React

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

PATCH 요청 (내용 수정하기)

 

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 [targetId, setTargetId] = useState("");
  const [content, setContent] = useState();

  // 서버로 부터 값 받아오는 함수
  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]); // 값 추가
    fetchTodos(); // 다시 값을 읽어와서 id 값을 부여함.
  };

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

  // 수정함수
  const onUpdateHandler = async () => {
    axios.patch(`http://localhost:4000/todos/${targetId}`, {
      title: content,
    });
    setTodos(
      todos.map((todo) => {
        if (todo.id == targetId) {
          // 아이디의 형이 달라서 동등연산자로 하면 작동함.
          return { ...todo, title: content };
        } else {
          return todo;
        }
      })
    );
  };

  useEffect(() => {
    // 마운트 되었을 때 실행할 로직, db로부터 값을 가져올 것이다.
    fetchTodos();
    return () => {
      // 언마운트 되었을 때 리턴할 값
    };
  }, []); // 어떤 state 가 변경될 때, 실행하는지 결정
  return (
    <>
      <div>
        <h1>수정 영역</h1>
        <input
          type="text"
          placeholder="수정할 아이디"
          value={targetId}
          onChange={(e) => setTargetId(e.target.value)}
        />
        <input
          type="text"
          placeholder="수정할 내용"
          value={content}
          onChange={(e) => setContent(e.target.value)}
        />
        <button onClick={onUpdateHandler}>수정</button>
        <br />
      </div>
      <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] instance 와 interceptor  (0) 2023.07.04
[React] Fetch 와 Axios  (0) 2023.07.04
[React] 비동기 통신 axios(delete)  (0) 2023.07.04
[React] 비동기 통신 axios(post)  (0) 2023.07.04
[React] 비동기 통신 axios(get)  (0) 2023.07.04