Vue.js - computed property not rendering in repeated list

It seems like the issue lies in the timing rather than being related to asynchronous operations. I'm currently iterating through an object and displaying a list of items. One of the values requires calculation using a method.

While the direct values on the item object display correctly, the calculated one doesn't show up consistently even though it's logged in the console.

I've attempted to re-render the list by changing keys without success. I also tried turning it into a computed property but encountered issues where it wasn't recognized as a function.

<ul>
  <li
    v-for="(item, index) in list"
    :key="index"
    class="list-wrap"
  >
    <span> 
      {{ item.name }} <---- this value displays every time.
    </span>
      <span class="location">
        {{ getLocation(item.Location[0]) }} <---- this calculated value only shows sporadically.
      </span>
  </li>
</ul>

Method for getLocation:

methods: {
  getLocation(loc) { // ID retrieved from item in loop
    this.locations.forEach((location) => { // Iterate through locations object, match ID, return location name.
      let match;
      if (location.id === loc) {
        match = location.name;
        console.log(match); <---- appears correct on each refresh
        return match; <--- not rendering
      }
    });
  },
},

// List is generated in an asynchronous API call

async getCurUserTransfers() {
  await airtableQuery
    .getTableAsync("Transfers", 100, "Grid view")
    .then((data) => {
      this.list = data.filter( // List is a filtered table.
        (transfer) =>
          transfer.fields.User === this.curUserNicename ||
          transfer.fields.User === this.curUserDisplayName
      );
    });
},

Answer №1

To optimize calculated fields, it is recommended to utilize computed properties. One approach is to create a computed property named listWithLocation and iterate through it as follows:

computed:{
     listWithLocation(){

     return this.list.map( item=>{
        item.itemLocation=this.getLocation(item.Location[0]);// add field itemLocation and use the method already defined
         return item;
    }) 
}
}

Here is how you can structure your template:

<ul>
  <li
    v-for="(item, index) in listWithLocation"
    :key="index"
    class="list-wrap"
  >
    <span> 
      {{ item.name }} 
    </span>
      <span class="location">
        {{item.itemLocation}}
      </span>
  </li>
</ul>

This is the method used within the script:

methods: {
  getLocation(loc) { 
    return this.locations.find((location) => { // this returns the matched location
     
     return location.id === loc;
      
    });
  },
},

Answer №2

The return statement within the anonymous function nested in your method is preventing any returned values from the main function.

If you require computed fields, they must be declared in a specific array known as computed. For more information, visit this link.

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

Displaying search results seamlessly on the same page without any need for reloading

I am looking to create a search engine that displays results without the need to refresh the page. I have come across using hash as a potential solution, but I don't have much knowledge about web programming. So far, with the help of tutorials, I have ...

Preventing Content Changes When Ajax Request Fails: Tips for Error Checking

I was struggling to find the right words for my question -- My issue involves a basic ajax request triggered by a checkbox that sends data to a database. I want to prevent the checkbox from changing if the ajax request fails. Currently, when the request ...

What could be causing me to not receive the prepackaged error messages from Angular in my WebStorm 8?

Having some trouble here... my angular errors are always so cryptic, like this: I usually manage to figure out the issue on my own, but I'm really hoping someone can offer guidance on how to get those nice error messages that angular supposedly displ ...

Mastering the Art of Leveraging Conditionals in JavaScript's Find Function

I'm curious about the implementation of an if statement in the JavaScript find function. My objective is to add the class "filtered-out" to the elements in my cars array when their values do not match. cars.map(car => active_filters.find(x => ...

How can I assign integer values to specific child elements after splitting them?

Below is the HTML code that needs modification: <div class="alm-filter alm-filter--meta" id="alm-filter-1" data-key="meta" data-fieldtype="checkbox" data-meta-key="Cate" data-meta-compare="IN" data-meta-type="CHAR"> <ul> <li class=" ...

Having difficulty ensuring DayJs is accessible for all Cypress tests

Currently embarking on a new Cypress project, I find myself dealing with an application heavily focused on calendars, requiring frequent manipulations of dates. I'm facing an issue where I need to make DayJs globally available throughout the entire p ...

Is there a way to refresh a webpage without the need to reload it

Imagine a scenario where a tab on a website triggers the loading of a specific part of the webpage placed within a div. For example, clicking on a tab may trigger the loading of a file named "hive/index.php". Now, if a user selects an option from an auto ...

Display the entire HTML webpage along with the embedded PDF file within an iframe

I have been tasked with embedding a relatively small PDF file within an HTML page and printing the entire page, including the PDF file inside an iframe. Below is the structure of my HTML page: https://i.stack.imgur.com/1kJZn.png Here is the code I am usin ...

Easily iterate through the <li> elements using jQuery and append them to the <datalist> dynamically

My jQuery loop seems to be malfunctioning as it's not showing the values of my li elements. Instead, I'm seeing [object HTMLElement] in my input search bar. <div id="sidebar-wrapper"> <input type="text" list="searchList" class="searc ...

Unable to retrieve the text enclosed between the:: before and after the:: marker

I attempted this using the XPATH finder in Chrome, and it highlighted the element. However, when running my Selenium script, I received the following error: Caused by: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: ...

Attributes of an object are altered upon its return from a Jquery function

After examining the following code snippet: index.html var jsonOut = $.getJSON("graph.json", function (jsonIn) { console.log(jsonIn); return jsonIn; }); console.log(jsonOut); The graph.json file contains a lengthy JSON fo ...

Access the value retrieved from a form on the previous page using PHP

I'm struggling with extracting values from radio buttons on a previous page. Currently, my HTML and PHP code works fine with the search bar, which is the first form below. However, I'd like to add radio button filters below the search bar. <s ...

Using Jquery to detect if there are any Space characters in the user input

In my form, users are required to set up a new Username. The problem arises when they include a space in their username, which I want to prevent. Currently, I am able to detect the presence of a space with this code: var hasSpace = $('#usernameValue ...

How can I confirm if a class is an instance of a function-defined class?

I have been attempting to export a class that is defined within a function. In my attempts, I decided to declare the class export in the following way: export declare class GameCameraComponent extends GameObject { isMainCamera: boolean; } export abstra ...

Access exclusive content by subscribing now!

How can I return a reference to a subject from a service without allowing the receiver to call .next() on the subject? Let's say there is a service with a subject that triggers new events. class ExampleService { private exampleSubject = new Subjec ...

Encountering a "400 Bad Request" error when using Ajax within WordPress

I've been trying to submit a form using Ajax within a plugin. I had two plugins, the first one was initially working but has stopped now and I can't seem to find any errors. I don't think the issue lies in the code itself, but I'm feeli ...

After upgrading to version 4.0.0 of typescript-eslint/parser, why is eslint having trouble recognizing JSX or certain react @types as undefined?"

In a large project built with ReactJs, the eslint rules are based on this specific eslint configuration: const DONT_WARN_CI = process.env.NODE_ENV === 'production' ? 0 : 1 module.exports = { ... After upgrading the library "@typescript-es ...

Differences Between 'this' and 'self' in Classes

I am currently working with ES6 Classes and I'm struggling to grasp why I am able to access the this variable within one of the methods. //CODE class Form{ constructor(){ var self = this; } assemble(){ log(self); ...

Javascript: A guide on passing an object through multiple nested functions

Hey fellow developers, I'm facing a challenge in my code and seeking advice from the experts out there. I'm attempting to retrieve JSON data from a specific URL, as shown below, and utilize it in a React component outside of the getWeather() fun ...

Issue with MUI Data Grid sorting: Data Grid sortComparator function returning undefined

I'm attempting to organize data with nested values in a data grid, but I keep receiving 'undefined' on the sortComparator of Data Grid Columns. Code: Column Data Setup: { headerName: 'Title', field: `${this.props.type} ...