본문 바로가기
Do it Node.js/React BackEnd

4. 연락처 수정 페이지, 삭제

by 갱생angel 2024. 3. 17.

연락처를 수정하고 삭제

  -update.js 페이지 추가

  -alert 문이 출력되게 수정

 

-백엔드-

 

controllers - <cantactController-2.js>

(...)

//Get get contact, /contact/:id
const getContact = asynchHandler(async (req, res) => {
  const contact = await Contact.findById(req.params.id);
  res.status(200).send(contact);
});

//Put update contact, /contact/:id
const updateContact = asynchHandler(async (req, res) => {
  const { name, email, phone } = req.body;
  const contact = await Contact.findByIdAndUpdate(
    req.params.id,
    { name, email, phone },
    { new: true }
  );
  res.status(200).send(contact);
});

//Delete delete contact, /contact/:id
const deleteContact = asynchHandler(async (req, res) => {
  await Contact.findByIdAndDelete(req.params.id);
  res.status(200);
});

(...)

-프론트엔드-

 

index.js

App.js

component

  -header.js

page

  -main.js

  -add.ejs

  -update.js

css

  -style.css

 

<App.js> : 수정 페이지 라우터

import React from "react";
import Main from "./page/main";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Add from "./page/add";
import Update from "./page/update";

function App() {
  return (
    <div>
      <BrowserRouter>
        <Routes>
          <Route index element={<Main />} />
          <Route path="/add" element={<Add />} />
          <Route path="/:id" element={<Update />} /> 
        </Routes>
      </BrowserRouter>
    </div>
  );
}

export default App;

 

page - <main.js> : 해당 연락처 수정 페이지로 이동, 삭제

import React, { useEffect, useState } from "react";
import axios from "axios";
import "../css/style.css";
import Header from "../component/header";
import { useNavigate } from "react-router-dom";

function Main() {
  const navigate = useNavigate();

  const [lists, setLists] = useState([]);

  const deleteData = (deleteId) => { //삭제 함수
    alert("삭제되었습니다.");
    axios.delete(`http://localhost:8080/contact/${deleteId}`);
  };

  const goToAdd = () => {
    navigate("/add");
  };

  useEffect(() => {
    axios
      .get("http://localhost:8080/contact")
      .then((res) => setLists(res.data));
  });

  return (
    <div>
      <Header />
      <div className="site-main">
        <div className="button-box">
          <button onClick={goToAdd}>+ 연락처 추가</button>
        </div>
        <table className="table">
          <thead>
            <tr>
              <th>이름</th>
              <th>이메일</th>
              <th>전화번호</th>
              <th>&nbsp;</th>
            </tr>
          </thead>
          <tbody>
            {lists.map((list, index) => {
              return (
                <tr key={index}>
                  <td>{list.name}</td>
                  <td>{list.email}</td>
                  <td>{list.phone}</td>
                  <td>
                    <button onClick={() => navigate(`/${list._id}`)}>
                      수정
                    </button>
                    <button onClick={() => deleteData(list._id)}>
                      삭제
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

export default Main;

 

page - <update.js> : 연락처 수정 페이지

useParams() : 파라미터 값(id)을 가져오는 훅

import React, { useEffect, useState } from "react";
import Header from "../component/header";
import axios from "axios";
import { useNavigate, useParams } from "react-router-dom";

function Update() {
  const { id } = useParams(); //id 값 가져오기
  const navigate = useNavigate();

  const [updateName, setModifyName] = useState(""); //수정할 이름
  const [updateEmail, setModifyEmail] = useState(""); //수정할 이메일
  const [updatePhone, setModifyPhone] = useState(""); //수정할 연락처

  const changeModifyName = (e) => {
    setModifyName(e.target.value);
  };
  const changeModifyEmail = (e) => {
    setModifyEmail(e.target.value);
  };
  const changeModifyPhone = (e) => {
    setModifyPhone(e.target.value);
  };

  const updateForm = (e) => { //연락처 수정
    e.preventDefault();
    const updateUserData = {
      name: updateName,
      email: updateEmail,
      phone: updatePhone,
    };
    if (updateName === "" || updateEmail === "" || updatePhone === "") {
      alert("입력해주세요.");
    } else {
      axios
        .put(`http://localhost:8080/contact/${id}`, updateUserData) //PUT 보내기
        .then(() => goToMain())
        .then(() => {
          alert("수정되었습니다."); //alert문 추가
        });
    }
  };

  const goToMain = () => {
    navigate("/");
  };

  useEffect(() => {
    axios.get(`http://localhost:8080/contact/${id}`).then((res) => { //이전 내용 가져오기
      setModifyName(res.data.name);
      setModifyEmail(res.data.email);
      setModifyPhone(res.data.phone);
    });
  }, [id]);

  return (
    <div>
      <Header />
      <div className="site-main">
        <div className="button-box">
          <button onClick={goToMain}>연락처 목록</button>
        </div>
        <h2>연락처 수정</h2>
        <p>연락처 정보를 수정합니다.</p>
        <form onSubmit={updateForm}>
          <div className="user-info">
            <div>
              <label>이름</label>
              <input
                type="text"
                value={updateName || ""}
                onChange={changeModifyName}
              />
            </div>
            <div>
              <label>메일 주소</label>
              <input
                type="text"
                value={updateEmail || ""}
                onChange={changeModifyEmail}
              />
            </div>
            <div>
              <label>전화번호</label>
              <input
                type="text"
                value={updatePhone || ""}
                onChange={changeModifyPhone}
              />
            </div>
            <button type="submit">수정하기</button>
          </div>
        </form>
      </div>
    </div>
  );
}

export default Update;

 

page - <add.js> : 연락처 수정 페이지

import React, { useState } from "react";
import Header from "../component/header";
import { useNavigate } from "react-router-dom";
import axios from "axios";

function Add() {
  const navigate = useNavigate();

  const [name, setName] = useState();
  const [email, setEmail] = useState();
  const [phone, setPhone] = useState();

  const changeName = (e) => {
    setName(e.target.value);
  };
  const changeEmail = (e) => {
    setEmail(e.target.value);
  };
  const changePhone = (e) => {
    setPhone(e.target.value);
  };

  const addForm = (e) => {
    e.preventDefault();
    const userData = { name: name, email: email, phone: phone };
    if (name === undefined || email === undefined || phone === undefined) {
      alert("입력해주세요.");
    } else {
      axios
        .post("http://localhost:8080/contact/add", userData)
        .then(() => goToMain())
        .then(() => {
          alert("저장되었습니다."); //alert 문 추가
        });
    }
  };

  const goToMain = () => {
    navigate("/");
  };

  return (
    <div>
      <Header />
      <div className="site-main">
        <div className="button-box">
          <button onClick={goToMain}>연락처 목록</button>
        </div>
        <h2>연락처 추가</h2>
        <p>연락처 정보를 추가합니다</p>
        <form onSubmit={addForm}>
          <div className="user-info">
            <div>
              <label>이름</label>
              <input type="text" value={name || ""} onChange={changeName} />
            </div>
            <div>
              <label>메일 주소</label>
              <input type="text" value={email || ""} onChange={changeEmail} />
            </div>
            <div>
              <label>전화번호</label>
              <input type="text" value={phone || ""} onChange={changePhone} />
            </div>
            <button type="submit">저장하기</button>
          </div>
        </form>
      </div>
    </div>
  );
}

export default Add;

'Do it Node.js > React BackEnd' 카테고리의 다른 글

6. 로그인 페이지  (0) 2024.03.20
5. 회원가입 페이지  (0) 2024.03.19
3. 연락처 추가 페이지, react-router-dom  (0) 2024.03.15
2. 연락처 목록 페이지, Axios  (0) 2024.03.14
1. 백엔드 연결  (0) 2024.03.14