Extract the "_id" value from the array in the v-for loop and then store and reuse it in the data object // using vue-cli

Currently, I am iterating through [postArray] to retrieve various posts, each of which has its own unique "_id". My goal is to utilize this "_id" to add likes to the corresponding post.

This is the v-for loop I am using:

<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>

Here is where I intend to store the id in postId within my data:

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

In addition, these are the methods I have defined 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);
},

Furthermore, you can view the console log screenshot here.

[enter image description here][2]

Answer №1

Make sure to pass the _id value to your function:

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

Then, capture and use it in your method:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating with Express 4

Currently, I am in the process of implementing Passport for user signup by referring to this helpful guide: https://scotch.io/tutorials/easy-node-authentication-setup-and-local Overall, everything is functioning properly except for one issue - after a su ...

Adaptively linking to the property of a deeply nested object

Attempting to bind to a property of a nested object using [(ngModel)], but facing the challenge that the path to the property is dynamically set. Consider the following three classes: class A { p1: C constructor() { p1 = new C("A") } } class B { p2: ...

When the React functional component changes its state, it triggers the un-mounting and re-mounting of its parent

I created a functional component that allows for toggling the visibility of a password field using a small button that switches between closed and opened eye images. The issue I'm facing is that even though the parent does not have any affected state ...

Sharing Global Variables in Node.js: What's the Best Way to Pass Them into Required Files?

Recently, I decided to organize my gulpfile.js by splitting it into multiple files within a /gulp folder. However, I encountered an issue when trying to pass a variable debug (boolean) into these files to control the behavior of the gulp command being incl ...

Defining data types for an array of objects in a useState hook

I'm having trouble understanding the issue with my code. interface dataHistory { data: string, before: string | number, after: string | number, } I have an interface defined outside of the Functional Component and inside I specify its struct ...

I'm having trouble getting Tailwind CSS colors to work with my Next.js components. Any tips on how to apply background colors

https://i.stack.imgur.com/8RGS3.png https://i.stack.imgur.com/FRTOn.png Hey there! I'm currently experimenting with using Tailwind background colors in my Next.js project. However, I'm facing an issue where the background color is not being appl ...

An argument error in IE 8 caused by an invalid procedure call

Is there a way to access the opener's class in a child window created using window.open? This works smoothly in W3C browsers, but fails in IE 8. On the other hand, I tested using an iframe and it seems to work fine across all browsers. The main goal o ...

Incorrect positioning on canvas

Is there a way to adjust text alignment within a canvas? Currently, my text is centered. However, when I change the text size, the alignment gets thrown off. Here is the code snippet: <canvas id="puzzle" width="480" height="480"></canvas> ...

Adding Multiple Items to an Express Endpoint

I have a requirement to store multiple objects in my mongo database within an express route. Currently, the process is smooth when I post individual objects (such as ONE casino), as shown below. Instead of repeating this numerous times, I am seeking assist ...

Switching Next.js route using pure JavaScript

Currently, I am facing a challenge in changing the route of a Next.js application using vanilla Javascript. In order for the code to be compatible with Chrome Dev Tools, I cannot dynamically change the route with Next.js and instead must find a solution us ...

What could potentially be the reason behind the incapability of the next.js Image component to transform the svg into a

Unique Context I recently developed a minimalist Hero + Navbar using Next.js. The site utilizes the powerful next.js Image component to display images. Surprisingly, all three images on the website, which are in .webp format, load instantly with a size of ...

React Navigation - CSS file identified as "text/html" after introducing a dynamic route parameter (/userId)

Our customized stylesheet "styles.css" seems to be incorrectly identified with the MIME type "text/html", even though it is specified as: rel="stylesheet" type="text/css" This issue only arises when navigating to routes with a variable parameter such as ...

Utilizing jQuery show() and hide() methods for form validation

I created a form to collect user details and attempted to validate it using the jQuery hide and show method. However, I seem to be making a mistake as the required functionality is not working correctly. What am I missing? I have searched for solutions on ...

What is the best way to style radio boxes in HTML to resemble checkboxes and display X's when selected?

I'm looking to create a form with radio boxes that resemble checkboxes and display a glyphicon x when selected. I've experimented with various solutions such as: input[type="radio"] { -webkit-appearance: checkbox; /* Chrome, ...

Is it no longer possible to create custom linked Context Menus in Tabulator 5?

After using Tabulator for a few years, we have decided to switch over to Angular v13 and upgrade to the new Tabulator 5.x. In our previous implementation, we had set up a custom ContextMenu in the Table Column Definition like this: contextMenu: this.TableR ...

Modify the css with JQUERY when there are no rows inside the tbody section

Is it possible to change the css using jquery if there are no rows in the table body? I have attempted this but my current approach is not working. I tried adding an alert within the if statement, but the alert did not appear. My goal is to hide the table ...

Using jQuery UI Tabs to Dynamically Select a Tab Based on a Link

Recently, I have been exploring the idea of using a script to open a specific tab: $('.tofour').click(function() { // bind click event to link $tabs.tabs('select', 3); // switch to third tab return false; }); However, my dilem ...

Routing WebSocket connections with Node.js

Currently, I am in the process of developing a chat application for my company which will run on node js with websocket (ws). The app is designed to cater to various departments within the organization, each with its own set of users. My goal is to ensure ...

Calculating values within dynamically generated elements requires utilizing JavaScript to target and extract the

I am working on creating input fields inside an HTML table using Vue.js. On click of a button, I want to perform some calculations based on the input values. However, it seems that the calculations are not happening as desired. What I have attempted so fa ...

Is there a way to adjust the timepicker value directly using the keyboard input?

Is there a way to control the material-ui-time-picker input using the keyboard instead of clicking on the clock? This is my current code: import React, { Component } from "react"; import { TimePicker } from "material-ui-time-picker"; import { Input as Ti ...