WEB(Front-End)/React 시작
15. DELETE : DELETE 메서드 이용
RoarinGom
2021. 11. 2. 23:19
1. 클릭 이벤트로 함수 연결하고 del() 함수 정의
function del(){
if(window.confirm('삭제하시겠습니까?')){
fetch(`http://localhost:3001/words/${word.id}`,{
method:"DELETE",
})
}
}
2. 삭제요청을 하고 ok 응답을 받으면 컴포넌트를 다시 랜더링 하기 (null을 리턴)
import { useState } from "react";
export default function Word({word:w}){
const [word,setWord]=useState(w);
const [isShow,setIsShow]=useState(false);
const [isDone,setIsDone]=useState(w.isDone);
function toggleShow(){
setIsShow(!isShow);
}
function toggleDone(){
fetch(`http://localhost:3001/words/${word.id}`,{
method:'PUT',
headers:{
'content-type':'application/json',
},
body:JSON.stringify({
...word,
isDone:!isDone
}),
})
.then(res=>{
if(res.ok){
setIsDone(!isDone);
}
});
}
function del(){
if(window.confirm('삭제하시겠습니까?')){
fetch(`http://localhost:3001/words/${word.id}`,{
method:"DELETE",
}).then(res=>{
if(res.ok){
setWord({id:0});
}
})
}
}
if (word.id===0){
return null;
}
return(
<tr className={isDone?"off":""}>
<td>
<input type="checkbox" checked={isDone} onChange={toggleDone}></input>
</td>
<td>
{word.eng}
</td>
<td>
{isShow && word.kor}
</td>
<td>
<button onClick={toggleShow}>뜻 {isShow?'숨기기':'보기'}</button>
<button onClick={del} className="btn_del">삭제</button>
</td>
</tr>
);
}