A peculiar issue is occurring in Vue.js where a value within a v-for loop seems to be losing association with the intended array

During my third day of working with Vue.js, I decided to create a basic application for requesting car keys in a service department. Although I am aware that there are areas in the code that could be improved, I encountered a specific issue that I need assistance with. The time function within the code updates every minute to track elapsed time. However, when I submit a new key request, the elapsed time from the first request seems to carry over to the second request instead of starting fresh. This issue may be related to how the code is structured, but despite trying various solutions, I have been unable to resolve it. Any guidance on this matter would be greatly appreciated.

<template>
    <div class="row">
        <div class="card col-md-6" v-for="(key, index) in keys" :key="index">
          <div class="card-body">
            <h5 class="card-title">Service Tag: {{ key.service_tag }}</h5>
            <p class="card-text"> {{time}} {{key.reqTimestamp}}min</p>
            <p class="invisible">{{ start(key.reqTimestamp) }}</p>
            <p class="card-text">Associates Name: {{key.requestor_name}}</p>
            <p class="card-text">Model: {{key.model}}</p>
            <p class="card-text">Color: {{key.color}}</p>
            <p class="card-text">Year: {{key.year}}</p>
            <p class="card-text">Comments: {{key.comments}}</p>
            <p class="card-text">Valet: {{key.valet}}</p>
            <input class="form-control" v-model="key.valet" placeholder="Name of the person getting the car...">
            <button
              @click="claimedKey(key.id, key.valet)"
              type="submit" 
              class="btn btn-primary"
              >Claim</button>
              <button v-if="key.valet !== 'Unclaimed'"
              @click="unclaimedKey(key.id, key.valet)"
              type="submit" 
              class="btn btn-primary"
              >Unclaim</button>
            <button class="btn btn-success" @click="complete(key.id)">Complete</button>
          </div>
      </div>
<!-- END OF CARD -->
<!-- START OF FORM -->
      <div class="row justify-content-md-center request">
        <div class="col-md-auto">
          <h1 class="display-4">Operation Tiger Teeth</h1>
          <form class="form-inline" @submit="newKey(service_tag, requestor_name, comments, model, year, color, valet, reqTimestamp)">
            <div class="form-group col-md-6">
           <!-- code continued -->

My ultimate goal is to ensure that the elapsed time is correctly associated with each individual key request.

Answer №1

There are some problematic lines in the template that need to be addressed:

<p class="card-text"> {{time}} {{key.reqTimestamp}}min</p>
<p class="invisible">{{ start(key.reqTimestamp) }}</p>

The use of start in this context is causing side-effects, which is not ideal for rendering a component. It changes the value of startTime, leading to a change in time. It's surprising that this isn't triggering a warning for infinite rendering recursion...

Instead of modifying values during rendering, it's better to utilize the relevant data for the current item, referred to as key. A method can be introduced to calculate the elapsed time based on a given key:

methods: {
  elapsedTime (key) {
    const timestamp = key.reqTimestamp;
    const startTime = timestamp.seconds * 1000;

    return Math.floor((this.currentTime - startTime) / 60000);
  }
}

This method combines functionalities of both start and time, without making any changes to this.

You can now call this method within the template:

<p class="card-text"> {{elapsedTime(key)}} {{key.reqTimestamp}}min</p>

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

Extract the value from JSON data

I am faced with the challenge of extracting the value of slug from each child in a JSON dataset. The issue lies in the fact that I cannot predict how many children will be generated whenever new data is received. The generation of nested children is dynam ...

I am unable to apply CSS to style my <div> element

I've run into a snag with my coding project, specifically when attempting to style my div. Here is the code I have so far: All CSS rules are applying correctly except for the .chat rule. Can someone help me figure out what I'm doing wrong? var ...

Maintaining the active status of section 1 after the page is refreshed using Javascript and CSS

I have a total of 3 buttons and 3 hidden sections available, which can be seen in the image below: click here for image description Whenever one of the buttons is clicked, the respective section transitions from being hidden to becoming visible: click he ...

Retrieve a boolean value through an Ajax call from a C# function using T4MVC

I have a search bar on my website with the following code: <form onsubmit="return IsValidCustomer()"> <input class=" sb-search-input" placeholder="Search for a customer..." type="text" value="" name="search" id="search"> <input cl ...

Preventing AJAX/hash functionality for specific links exclusively within jQuery Mobile

I've come across some outdated solutions for this issue, but it seems they are no longer applicable to jQuery Mobile. My goal is to disable the AJAX/hashbang behavior for specific links only. I know that I can disable it globally like this: /** * ...

Issue with Gulp and Browserify task: Why is there no output?

I've set up the following task in my gulpfile.js gulp.task('default', ['browserify']) gulp.task('browserify', function () { return browserify('./public/js/x.js') .bundle() .pipe(source('y.js& ...

Is it possible to use a link's URL as the action for a modal form submission?

I am writing a Rails application that requires users to store credential information in the database... ...

Upon refreshing the page in Javascript, the element mysteriously vanishes without a trace

After implementing a function that should display "barProgress25" and hide "barProgress0" when a button is clicked, I encountered an issue. Upon clicking the button, the function works as intended but upon page refresh, "barProgres ...

Creating a dynamic d3 force layout with interactive features in an Angular environment

I am currently working on a website using Angular and D3, although I don't have much experience with either of them. My goal is to create a force layout that is interactive, allowing users to select nodes and display related information in a sidebar. ...

Retrieving the CSS property values for a specific element using Selenium

Imagine a scenario where I locate an element by its XPath using: WebElement element = driver.findElement(By.xpath("specific XPath")); While I can retrieve the value of a single CSS property with element.getCssValue("specific property"), is there a way to ...

Experiencing difficulties connecting with aspx while using Ext JS 4.2

Currently, I am facing an issue with making a call to an ASPX URL as the return keeps coming back as a failure. I have successfully used this URL in previous programming projects, but this is my first time utilizing it with Ext JS. Despite researching dif ...

React error: Objects cannot be used as children in React components

Upon trying to display data using REACT, an error message stating "Objects are not valid as a React child. If you meant to render a collection of children, use an array instead" is encountered. The issue arises when fetching records from a MongoDB collect ...

Contradictory jQuery extensions

After exploring this site as part of my web coding self-study, I decided to register so I could ask a specific question. Currently, I am in the process of developing my new website and ran into an issue on a test page (www.owenprescott.com/home.html). The ...

Converting HTML widget code to NEXTjs code for integration in an application (CoinMarketCap Price Marquee Ticker)

Having trouble integrating the CoinMarketCap Price Marquee Ticker Widget into my NEXTjs app. I'm outlining my process and hoping for some suggestions from others who may have attempted this. Template Code: To embed the widget in an HTML page, here is ...

The Mystery of the Undefined Return Value in JavaScript's Map Function

My array contains around 1000 elements. I'm encountering a situation where the map function returns undefined for certain indexes. Is there a method to only retrieve values that meet a specific condition? I want to filter out elements with values less ...

Traverse through a collection of objects

I am facing a challenge with an array of objects (~650) structured like this: [1: {firstName: "Hello", lastName: "World", shortName: "h.world", ...some other items }, 2: {firstName: "John", lastName: "Doe", shortName: "j.doe", ...some other items }] ...

Updating a property in an object within an Angular service and accessing it in a different controller

I am currently utilizing a service to transfer variables between two controllers. However, I am encountering difficulties in modifying the value of an object property. My goal is to update this value in the first controller and then access the new value in ...

Troubleshooting VueJS, Electron, and Webpack integration with Hot Reload feature

I have been immersed in a new project that involves utilizing Electron, VueJS, and Webpack for HMR functionality. Unfortunately, I am encountering difficulties with the Hot Module Replacement feature not working as expected. Here is my current configurati ...

What is the most effective way to extract the value of a "$3" element using Selenium in Python?

I am facing a challenge in fetching an element from the netlify dashboard. The code I have currently grabs the base element that the web developers have set, indicating that it gets updated with javascript. However, I am having trouble accessing this updat ...

Sending a multi-level property object to the controller in a post request

I am facing a challenge where I need to transfer an object from the view to the controller, and the model comprises a list of objects, each containing another list of complex objects. Let's consider the following models: public class CourseVm { p ...