<React> CRUD

yezee·2022년 12월 1일
0

React

목록 보기
15/23
post-thumbnail

베포사이트-https://voca-crud.netlify.app/

C:create(생성)
R:read(읽기)
U:update(갱신)
D:delete(삭제)

📌 POST method

Post로 생성하면 자동으로 id가 부여된다

import React, { useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import useFetch from '../hooks/useFetch';

function CreateWord() {
  const days = useFetch('http://localhost:3004/days'); //커스텀훅으로 fetch해왔다
  const navigate = useNavigate();

  function onSubmit(e) {
    e.preventDefault();

    fetch(`http://localhost:3004/words/`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json', //보내는 리소스의 타입을 의미
      },
      body: JSON.stringify({ //추가할 정보를 body에 넣어준다
        day: dayRef.current.value, //ref훅을 사용해서 값을 받는다
        eng: engRef.current.value,//ref훅을 사용해서 값을 받는다
        kor: korRef.current.value,//ref훅을 사용해서 값을 받는다
        isDone: false, //isDone은 false를 기본값으로 한다
      }),
    }).then((res) => {
      if (res.ok) {
        alert('생성이 완료 되었습니다');
        navigate(`/day/${dayRef.current.value}`); //단어를 저징한 해당페이지로 이동
      }
    });
  }

  //ref는 돔요소가 생성된 후 접근이 가능하다
  const engRef = useRef(null);
  const korRef = useRef(null);
  const dayRef = useRef(null);

  return (
    <form onSubmit={onSubmit}>
      <div className='input_area'>
        <label>Eng</label>
        <input type='text' placeholder='computer' ref={engRef} />
      </div>
      <div className='input_area'>
        <label>Kor</label>
        <input type='text' placeholder='컴퓨터' ref={korRef} />
      </div>
      <div className='input_area'>
        <label>Day</label>
        <select ref={dayRef}>
          {days.map((day) => (
            <option key={day.id}>{day.day}</option>
          ))}
        </select>
      </div>
      <button>저장</button>
    </form>
  );
}

export default CreateWord;

📌 PUT method

기존에는 단순한 toggle함수로서 데이터를 수정하는 것이 아니라 state로 현재 상태를 변경하는 것만 가능(새로고침 시 다시 원래로 상태가 돌아옴->데이터의 변화가 없기 때문에)

function Word({ word }) {
  const [isDone, setIsDone] = useState(false); //state값이 true이거나 false
 const toggleDone = () => {
     setIsDone(!isDone);
  }
 }

PUT메소드를 사용하면 수정된 정보를 body에 넣어 보내준다

function Word({ word }) {
   const [isDone, setIsDone] = useState(word.isDone); //수정될 값을 넣어준다
  const toggleDone = () => {
 fetch(`http://localhost:3004/words/${word.id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json', //보내는 리소스의 타입을 의미
      },
      body: JSON.stringify({ //수정을 위한 정보를 body에 넣어준다
        ...word, //기존데이터에
        isDone: !isDone, //수정되는 값을 추가
      }),
    }).then(res=>{
        if(res.ok){
          setIsDone(!isDone) //응답이 ok면 상태값을 변경해준다
        }
      });
  } 
}

res.ok는 인터페이스의 ok읽기 전용 속성 Response에는 응답이 성공했는지 여부를 나타내는 부울이 포함된다(상태 200-299범위)

📌 Delete method

function Word({ word: w }) { //word를 구조분해할당해서 w라는 새로운 변수명으로 할당해준다
  const [word, setWord] = useState(w); //word를 state로 만든다
  
  function del() {
    if (window.confirm('삭제하시겠습니까?')) { //alert창
      
      fetch(`http://localhost:3004/words/${word.id}`, {
        method: 'DELETE',
      }).then((res) => {
        if (res.ok) {
          setWord({ id: 0 });
        }
      });
    }
  }

  if (word.id === 0) {
    return null; //id가 0이면 기존 데이터를 날리고 null로 하겠다
  }
}
profile
아 그거 뭐였지?

0개의 댓글