[Vuejs]-Do VueJS indexes update when newly added items are added?

0👍

ahhh … i see now what you mean and how you’re using the index after the API has been triggered. I think you are correct in that if someone updates the original post array before the response is complete, the index will not be enough to accurately update the posts array with the response description.

// Your original code
updatePost: function(post, index) { 
  axios.post(‘/post’, { Id: post.id })
    .then(response => {
      post[index].description = response.data.description
  });
}

I would probably not worry about using the index at all as a method param and modify your logic to look something like this:

data() {
  return {
    posts: []
  }
},

methods: {
  updatePost: function(post) {
    axios.post('/post', { Id: post.id })
      .then(response => {
        let originalPost = this.posts.find(op => op.id == post.id);
        originalPost.description = response.data.description;
      });
  }
}

Then, when you initially call the updatePost method, you would just pass the specific array element index you want to update. So something like this:

this.updatePost(this.posts[0])

This way, whenever the API response comes through, you are looking up the proper array element to update by matching the id in the post object, rather than using the index of the array. Because, yes, if the posts[] array has changed before the response comes back, you can no longer rely on the array index to identify the correct post object to update.

Leave a comment