삐옹

state 불변성을 지켜라(댓글 달기) 본문

React

state 불변성을 지켜라(댓글 달기)

삐옹 2022. 6. 16. 17:42
const DetailComment = ({ boardId }) => {
  const [newComment, setNewComment] = useState("");
  const [commentArray, setCommentArray] = useState([]);

  const updateComment = (e) => {
    setNewComment(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    const currentKey = localStorage.getItem("jwt-token");
    if (newComment === "") {
      alert("내용을 입력해주세요");
    } else {
      axios
        .post(
          `http://3.39.223.175/api/board/${boardId}/comment/`,
          { comment: newComment },
          {
            headers: {
              "Content-Type": `application/json`,
              Authorization: `Bearer ${currentKey}`,
            },
          }
        )
        .then((response) => {
          const nicknameData = response.data.createComment.nickname;
          const commentData = response.data.createComment.comment;
          setCommentArray((commentValueList) => [
            ...commentValueList,
            {
              nickname: nicknameData,
              comment: commentData,
            },
          ]);
        })
        .catch((error) => {
          console.log(error);
        });
    }
    setNewComment("");
  };
  
  return (
  ...
  )
  };

문제

댓글 달기

axios를 통해 받아온 객체 데이터를 어떻게 state 값에 업데이트 할까?

 

조건 

- 댓글의 내역을 모두 조회할 수 있어야 합니다