qliq
qliq

Reputation: 11807

How to update arrays in a vue.js loop reactively?

In a blog-like Vue.js app I'd like to update list of comments of a post with new comments, when a new comment is successfully posted to the server.

Here is my code:

<div v-for="(post, index) in posts" :key="index" >  
    <div>{{post.body}}</div>
    <div class="comments">
        <ul v-for="(c, j) in post.comments" :key="j" class="comment">                      
          <li>{{c.user_id}} : {{c.body}} </li>
        </ul>    
    </div>

     <div>                  
        <input type="text" v-on:keyup.enter="submitComment(post)" v-model="post.comment" placeholder=" Add your comment" />                  
     </div>
</div>

And the method:

  submitComment(post) {
    const formData = new FormData();
    formData.append('token', this.token);
    formData.append('pid', post.id);
    formData.append('body', post.comment);
    axios.post(this.BASE_URL + "/api/comment", formData)
    .then( (res)=> {
      console.log('Updated comments are', res.data.comments);
      this.$set(post, 'comment', res.data.comments) ; //Here is the problem
    })
    .catch( error => {  
      console.log(error);
    });
  }

Despite the fact that I receive the updated list of comments, empty results is rendered. How can I fix this?

Upvotes: 0

Views: 65

Answers (1)

slowFooMovement
slowFooMovement

Reputation: 568

as @blaz pointed out in the comments above, it looks like the error is from a typo in the $set method call as the property should be the plural comments not comment

Upvotes: 1

Related Questions