[ react ] 댓글 수정하기

Suji Kang·2023년 11월 15일
0

🐾 댓글 수정하기

컴포넌트를 만들어준다.



각각 isEdit이 3개 그려지고있다.

props로 보내주고
activityCommentSection.js

  <CommentListWrap>
                {
                    commentList.map((comment) =>
                        <CommentBlock
                            key={comment.id}
                            onDeleteClick={onDeleteClick}
                            comment={comment}
                        />)
                }
  </CommentListWrap>

props로 받고,
CommentBlock.js

import React, { useState } from 'react';
import { CommentItem, CommentHeader, CommentWriter, CommentDate, CommentBtn, Comment } from '../../styles/dashboard/activityComment.styles';

const CommentBlock = (props) => {
    let comment = props.comment;
    let onDeleteClick = props.onDeleteClick;

    const [isEdit, setIsEdit] = useState(false);
    const [content, setContent] = useState(comment.content);

    return (
        <CommentItem key={comment.id}>
            <CommentHeader>
                <CommentWriter>
                    작성자 id : {comment.writer_email}
                </CommentWriter>
                <CommentDate>(작성일){comment.created_date}</CommentDate>
                <CommentDate>(수정일){comment.updated_date}</CommentDate>
                {comment.owner &&
                    <CommentBtn
                        onClick={() => { onDeleteClick(comment.id) }}
                    >삭제</CommentBtn>
                }
            </CommentHeader>
             {isEdit ? <input
                onBlur={onEditClick}
                onChange={(e) => { setContent(e.target.value); }}
                value={content} /> :
                <Comment onClick={() => { setIsEdit(true) }} >{comment.content}</Comment>
            }
        </CommentItem>
    );
}
export default CommentBlock;

const onEditClick = async () => {
        //express 에게 수정할 댓글의 id와 수정할 내용을 보내준다.(수정요청)
        try {
            await axios.put('/api/comments', {
                commentId: comment.id,
                content
            });
        } catch (err) {
            alert('댓글수정 오류');
        }
    }

return(
   {isEdit ? <input
        onBlur={onEditClick}
        onChange={(e) => { setContent(e.target.value); }}
        value={content} /> :
        <Comment onClick={() => { setIsEdit(true) }} >{comment.content}</Comment>
   }
 );

blur이벤트가 발생했을때는 onBlur


app.js

app.put('/api/comments', async (req, res) => {
    const id = req.body.commentId; //리액트가 준 수정할 댓글 id
    const content = req.body.content; //리액트가 준 수정할 댓글 내용
    const token = req.headers.authorization.replace('Bearer ', '');
    const user = jwt.verify(token, process.env.JWT_SECRET);

    let sql = `
        UPDATE tbl_comments
        SET content = ?,
        updated_date = now()
        WHERE id = ?;
    `;
    try {
        let [result] = await pool.query(sql, [content, id]); //수정된 댓글의 id를 result에 담아준다.
        console.log(result);
        let [rows] = await pool.query('select * from tbl_comments where id = ?', [id]);
        res.json({
            ...rows[0], //0번째방을 리액트한테 응답
            owner: rows[0].writer_email === user.email
        }); //리액트한테 응답
    } catch (err) {
        res.status(500).json('mysql 오류발생');
    }
});

정상적으로 실행되면 (affectedRows 가 1 이됨)


const CommentBlock = (props) => {
    let onDeleteClick = props.onDeleteClick;

    const [comment, setComment] = useState(props.comment);
    const [isEdit, setIsEdit] = useState(false);
    const [content, setContent] = useState(comment.content);

    const { accessToken } = useContext(UserContext);
  
  const onEditClick = async () => {
        if (accessToken === null) return;
        //express 에게 수정할 댓글의 id와 수정할 내용을 보내준다.(수정요청)
        try {
            let res = await axios.put('/api/comments', {
                commentId: comment.id,
                content
            }, {
                headers: { Authorization: `Bearer ${accessToken}` }
            });
            //res.data -> 수정된 댓글이 객체로 들어온다.
            setIsEdit(false);
            setComment(res.data);
            alert('댓글수정 성공');
        } catch (err) {
            alert('댓글수정 오류');
        }
    }
  }

owner가 아니면 수정과 삭제는 되지않는다.

 {isEdit ? <input
                onBlur={onEditClick}
                onChange={(e) => { setContent(e.target.value); }}
                value={content} /> :
                <Comment onClick={() => {
                    if (!comment.owner) return;
                    setIsEdit(true)
                }} >{comment.content}</Comment>
            }
profile
나를위한 노트필기 📒🔎📝

0개의 댓글