2

I'm new to programming. I'm trying React and have function addComment which is executed when a user adds a comment to news.I need to create in this moment a property comments (array) and assign or push to this array inputCommentValue value. But right now I only rewrite 0 element of the array and can't add a new element. Can you please tell me where to put push method? Thank you!

var ARTICLES = [{
  title: "sit amet erat",
  text: "nam dui proin leo odio porttitor id consequat in consequat ut nulla sed accumsan"

}, {
  title: "pulvinar sed",
  text: "velit id pretium iaculis diam erat fermentum justo nec condimentum"
}]



addComment(index, inputCommentValue){
ARTICLES = [...ARTICLES], ARTICLES[index].comments=[inputCommentValue];
this.setState({ARTICLES:ARTICLES});
}
2
  • this ARTICLES in your state? Commented Jul 11, 2016 at 12:06
  • Yes, ARTICLES is my state. It is updated properly. My problem is that I can't understand how to define (create) array and use method concat on it in the same time. I tried something like this: ARTICLES = [...ARTICLES], ARTICLES[index].comments=[].concat(inputCommentValue); But it works only for first element, next time (when user adds next comment) it rewrites array because of this comments=[] Commented Jul 11, 2016 at 12:21

2 Answers 2

2

Let's say you have an object like this.

   foo : {
       bar : "x"
    }

To create an array, simply initialize it to an empty array.

foo.newArray = []

If you console.log(foo), you will now see this

foo : {
   bar : "x",
   newArray : []
 }

This means your foo object has an empty array called newArray. You can add elements to it using the push() method.

Push a variable like this foo.newArray.push(myVariable); Push a string like this foo.newArray.push("myString"); Push an object like this

 foo.newArray.push({
    "bar2" : "val2"
 });

For more information on arrays check W3schools

In your particular case, just do ARTICLES.push({})

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

1 Comment

Divyanth Jayaraj, thank you for this explanation! Now it is clearer for me!
1

assuming that data exist in component's state , then handler will look something like that

addComment(index, inputCommentValue){
    // copy array , for not mutate state
    let ARTICLES = [...this.state.ARTICLES];
    // check if comments not exist
    if(!ARTICLES[index].comments) ARTICLES[index].comments=[];
    // add new comment to array
    ARTICLES[index].comments.push(inputCommentValue);
    // update component with new articles
    this.setState({ARTICLES:ARTICLES});
}

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.