[react] 댓글추가 & 댓글 삭제

Suji Kang·2023년 11월 12일
0

🐾 댓글추가하기

  const [content, setContent] = useState('');
  
   const onCommentClick = async () => {
        try {
            await axios.post('/api/comments', {
                content,
                activityId: props.activityId
            },
                {
                    headers: { Authorization: `Bearer ${accessToken}` }
                }
            );
            alert('댓글작성 성공!');
            setContent('');
        } catch (err) {
            alert('댓글작성 오류');
        }
    }; //body에다가 content를 담아서 express로 보내준다.

  return (
 	 <CommentInput onChange={(e) => { setContent(e.target.value) }} value={content} />
   	 <CommentWriteBtn onClick={onCommentClick}>댓글달기</CommentWriteBtn>
    );

express로 가서 요청

app.post('/api/comments', async (req, res) => {
    const token = req.headers.authorization.replace('Bearer ', '');
    let user = jwt.verify(token, process.env.JWT_SECRET);

    const content = req.body.content;
    const activityId = req.body.activityId;

    let sql = `
        INSERT INTO tbl_comments
        (content, activity_id, writer_email)
        VALUES (?, ?, ?);
    `;
     try {
        let [result] = await pool.query(sql, [content, activityId, user.email]);
        let [rows] = await pool.query('select * from tbl_comments where id = ?', [result.insertId]);
        // console.log(rows);
        res.json({ ...rows[0], owner: rows[0].writer_email === user.email }); //리액트한테 응답 
    } catch (err) {
        console.error(err); 
        res.status(500).json('오류발생');
    }
});

여기서!문제는,
댓글작성은 성공되었는데 refresh해야만 보인다.

2가지방법

  • 새로고침을 강제로 시키거나
  • state변수에 추가

console.log(rows[0]);
👇
👉 여기서 owner을 추가한다. ( true 또는 false로)

   try {
         let res = await axios.post('/api/comments', {
                content,
                activityId: props.activityId
            },
                {
                    headers: { Authorization: `Bearer ${accessToken}` }
                } 
            );
            setCommentList([...commentList, res.data]); 
     // 🌟 기존 댓글(commentList)과, 새로운 댓글을 res.data에추가해준다.
	 // state변수 배열이 바뀌었으니깐. 
            alert('댓글작성 성공!');
            setContent('');

이제는 refresh안해도 바로 추가됨 👍


🐾 댓글 삭제하기

//댓글 id를 매개변수로 받아서 해당 id를 가진 댓글 삭제
    const onDeleteClick = async (commentId) => {
        let del = window.confirm('정말 삭제하시겠습니까?')
        console.log(del) // true or false 로 나온다.  취소를 누르면 false 삭제를 누르면 true.
        if (del === false) return; // false 라면 삭제하지 않는다. 

        // true 라면 삭제한다. (확인버튼을 누르면 삭제)
        // express 에게 삭제할 댓글의 id를 보내준다.(삭제요청)
        try {
            axios.delete('/api/comments', { data: { commentId } });
            alert('댓글삭제 성공');
        } catch (err) {
            alert('댓글삭제 오류');
        }
    }
    
     return (
        <section>
            <CommentInputWrap>
                <CommentInput onChange={(e) => { setContent(e.target.value) }} value={content} />
                <CommentWriteBtn onClick={onCommentClick}>댓글달기</CommentWriteBtn>
            </CommentInputWrap>
            <CommentListWrap>
                {
                    commentList.map((comment) => <CommentItem key={comment.id}>
                        <CommentHeader>
                            {comment.owner &&
                                <CommentBtn
                                    onClick={() => { onDeleteClick(comment.id) }}
                                >삭제</CommentBtn>
                            }
                        </CommentHeader>
                        <Comment>{comment.content}</Comment>
                    </CommentItem>)
                }
            </CommentListWrap>
        </section>
    );

app.js

app.delete('/api/comments/:id', async (req, res) => {
const id = req.body.id; //리액트가 준 삭제할 댓글 id
try{
    await pool.query('DELETE FROM tbl_comments WHERE id = ?', [id]);
    res.json('삭제완료');
}catch(err){
    console.error(err);
    res.status(500).json('오류발생');
}
});



하지만 여기서도 추가할때와 같이 refresh를 해야 삭제가된다.
state변수를 직접 바꿔준다,

 try {
        axios.delete('/api/comments', { data: { commentId } });
        setCommentList(commentList.filter((comment) => comment.id !== commentId)); 
        // commentList에서 comment.id가 commentId와 같지 않은 것들만 남긴다. (삭제된 댓글만 빼고 다시 commentList에 넣어준다.)  
        alert('댓글삭제 성공');
 }


그러면 이제 바로 refresh없이 삭제완료❗️

profile
나를위한 노트필기 📒🔎📝

0개의 댓글