0

Hello I am trying to add new comments everytime I click my onClick button. However when I add new comments I don't want the old comments to go away, so I decided that what I am going to do is add the values to array and just map through it. However the way I am adding values to my array its giving me multiple arrays everytime I click the button. I want to click the button and I want the new value to appear in next to the old value in the array. Please help me solve this problem.

 handleChangeComment(event) {
  const myValue = event.target.value;
  this.setState({
    commentArea: [myValue]
  })
}

handleClickComment = (e) => {
  e.preventDefault();
   this.setState(({ clicked }) => ({ clicked: clicked + 1 }));
   this.setState(({ commentClick }) => ({ commentClick: commentClick + 1 }))
   let comment = this.state.commentArea
   let newComment = comment
   let currentComment = this.state.commentInfo;      
   let newComments = currentComment;
   newComments.push(newComment);
   console.log(newComments)
   let commentClick = this.state.commentClick


  let postInfoCopy = JSON.parse(JSON.stringify(this.state.postInfo))
  postInfoCopy[commentClick].comment = [newComments]
  this.setState({
      postInfo: postInfoCopy
    }) 



}
1
  • Can we see the render() method? Commented Apr 20, 2020 at 0:27

1 Answer 1

1

You can solve by adding spread operator ... to the array to get it's value and concat it to an single array

handleClickComment = (e) => {
        e.preventDefault();
       this.setState(({ clicked }) => ({ clicked: clicked + 1 }));
       this.setState(({ commentClick }) => ({ commentClick: commentClick + 1 }))
       let comment = this.state.commentArea
       let newComment = comment
       let currentComment = this.state.commentInfo;      
       let newComments = [...currentComment, ...newComment]
       let commentClick = this.state.commentClick

let newComments = [...currentComment, ...newComment]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.