axios-post,delete,fetch

λ°•μ„œν˜„Β·2023λ…„ 9μ›” 13일
0
post-thumbnail
post-custom-banner

πŸ«§ν™”λ©΄ ꡬ성

πŸ“ App.jsx

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

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

  const fetchTodos = async () => {
    const { data } = await axios.get("http://localhost:4000/todos");
    setTodos(data);
  };

  useEffect(() => {
    // dbλ‘œλΆ€ν„° 값을 κ°€μ Έμ˜¬ 것이닀
    fetchTodos();
  }, []);

  return (
    <>
      <div>
        {/* input μ˜μ—­ */}
        <form>
          <input type="text" />
          <button>μΆ”κ°€</button>
        </form>
      </div>

      <div>
        {/* 데이터 μ˜μ—­ */}
        {todos ? (
          todos.map((item) => (
            <div key={item.id}>
              {item.id} : {item.title}
            </div>
          ))
        ) : (
          <p>Loading...</p>
        )}
      </div>
    </>
  );
}

export default App;


πŸ«§μΆ”κ°€, μ‚­μ œ, μˆ˜μ • κΈ°λŠ₯ κ΅¬ν˜„

πŸ“ App.jsx

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

function App() {
  const [todos, setTodos] = useState(null);
  const [inputValue, setInputValue] = useState({
    title: "",
  });
  const [targetId, setTargetId] = useState("");
  const [contents, setContents] = useState("");

  // 쑰회 ν•¨μˆ˜
  const fetchTodos = async () => {
    const { data } = await axios.get("http://localhost:4000/todos");
    setTodos(data);
  };

  // μΆ”κ°€ ν•¨μˆ˜
  const onSubmitHandler = async () => {
    axios.post("http://localhost:4000/todos", inputValue);
    // setTodos([...todos, inputValue]); // 화면에 id값이 λ°”λ‘œ λœ¨μ§€ μ•ŠλŠ”λ‹€.
    fetchTodos(); // DBλ₯Ό λ‹€μ‹œ μ½μ–΄μ˜¨λ‹€.
    setInputValue({ title: "" }); 
  };

  // μ‚­μ œ ν•¨μˆ˜
  const onDeleteButtonClickHandler = async (id) => {
    axios.delete(`http://localhost:4000/todos/${id}`);
    setTodos(
      todos.filter((item) => {
        return item.id !== id;
      })
    );
  };

  //μˆ˜μ • ν•¨μˆ˜
  const onUpdateButtonClickHandler = async () => {
    axios.patch(`http://localhost:4000/todos/${targetId}`, {
      title: contents,
    });

    setTodos(
      todos.map((item) => {
        if (item.id == targetId) {
          return { ...item, title: contents };
        } else {
          return item;
        }
      })
    );
  };

  useEffect(() => {
    // dbλ‘œλΆ€ν„° 값을 κ°€μ Έμ˜¬ 것이닀
    fetchTodos();
  }, []);

  return (
    <>
      <div>
        {/* μˆ˜μ • μ˜μ—­ */}
        <div>
          <input
            type="text"
            placeholder="μˆ˜μ •ν•  아이디"
            value={targetId}
            onChange={(e) => {
              setTargetId(e.target.value);
            }}
          />
          <input
            type="text"
            placeholder="μˆ˜μ •ν•  λ‚΄μš©"
            value={contents}
            onChange={(e) => {
              setContents(e.target.value);
            }}
          />
          <button onClick={onUpdateButtonClickHandler}>μˆ˜μ •</button>
          <br />
          <br />
          <br />
        </div>

        {/* input μ˜μ—­ */}
        <form
          onSubmit={(e) => {
            e.preventDefault(); // λ²„νŠΌμ„ λˆŒλ €μ„ λ•Œ μƒˆλ‘œκ³ μΉ¨μ„ λ§‰λŠ”λ‹€.

            // λ²„νŠΌ 클릭 μ‹œ , input에 λ“€μ–΄μžˆλŠ” κ°’(state)을 μ΄μš©ν•˜μ—¬ DB에 μ €μž₯(postμš”μ²­)
            onSubmitHandler();
          }}
        >
          <input
            type="text"
            value={inputValue.title}
            onChange={(e) => {
              setInputValue({
                title: e.target.value,
              });
            }}
          />
          <button type="submit">μΆ”κ°€</button>
        </form>
      </div>

      <div>
        {/* 데이터 μ˜μ—­ */}
        {todos ? (
          todos.map((item) => (
            <div key={item.id}>
              {item.id} : {item.title}
              &nbsp;&nbsp;&nbsp;
              <button onClick={() => onDeleteButtonClickHandler(item.id)}>
                μ‚­μ œ
              </button>
            </div>
          ))
        ) : (
          <p>Loading...</p>
        )}
      </div>
    </>
  );
}

export default App;

post-custom-banner

0개의 λŒ“κΈ€