Home > Software engineering >  get "_id" from [ ] in v-for loop and reuse it in data // vuecli
get "_id" from [ ] in v-for loop and reuse it in data // vuecli

Time:10-16

i'm looping in [postArray] to get some posts, each post have it's own "_id". And I want to reuse this "_id" to add likes to the correct post.

this is the v-for loop:

<div class="posts" v-for="(element, index) in postArray" :key="index">
    <p>{{ element.title }}</p>
    <p>{{ element.content }}</p>
    <p>{{ element.likes.length }}</p>
    <button @click="addLike">Add Like</button>
  </div>

this is the data were i want to store my the id in postId:

data() {
return {
  title: "",
  content: "",
  postArray: [],
  postId: "",
};

},

and this is the methods were i want to reuse the _id:

async addLike() {
  const url =
    "https://dw-s3-nice-master-cake.osc-fr1.scalingo.io/post/like";

  const options = {
    method: "POST",

    headers: {
      "Content-Type": "application/json",
      Authorization: "bearer "   localStorage.getItem("token"),
    },
    body: JSON.stringify({
      postId: this.postId,
    }),
  };
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
  this.postId = data.posts._id;
  console.log(this.postId);
},

also the screen of the console.log(data):

console.log screenshot

[enter image description here][2]

CodePudding user response:

Try to send _id to your method:

<button @click="addLike(element._id)">Add Like</button>

and then receive it:

async addLike(id) {
  ...
  postId: id,
  ...
  • Related