Sorting through a list post a retrieval action

Could you guys please help me understand why my code is not functioning properly?

I am receiving an array from my backend rails API, which is providing the data correctly. I have created an empty array where I filter the records based on their ID.

The filtering process works fine initially, but whenever I refresh the page, my filterRecords method fails to execute and returns an empty array.

Below is the code snippet where I loop through the array and display the description in my filteredRecords:

<h1
          class="content"
          v-for="(record, index) of filteredRecords"
          :key="index"
          :record="record"
          :class="{ 'is-active': index === activeSpan }"
        >
          
          <strong>{{ record.description }} </strong>
        </h1>

This is the filterRecords() method in computed properties:

computed: {
    ...mapGetters({
      id: "id"
    }),
    
    filteredRecords() {
      return this.records.filter(record => {
        return record.template_id === this.id;
      });
    }
  },

This is how I fetch data from the API:

created() {
    
    if (!localStorage.signedIn) {
      this.$router.replace("/");
    } else {
      this.$http.secured
        .get("/api/v1/records")
        .then(response => {
          this.records = response.data;
        })
        .catch(error => this.setError(error, "Something went wrong"));
      
    }
  },

Can anyone guide me on how to ensure that the records are fetched and then filtered when I reload the page (i.e., invoke the filteredRecords computed method)?

Thank you!

EDIT

Hello, the issue was with the comparison operator used in the filter function. It should be == instead of === since they are different data types.

Answer №1

Make sure to give this code a try

computed: {
    ...mapGetters({
      id: "id"
    }),
    
    filteredRecords: function () {
        let localId = this.id;
        let filtered = this.records.filter(record => {
            return record.template_id == localId;
        });
        console.log(localId);
        console.log(filtered);
        return filtered;
    }
},

If the above doesn't solve the issue, consider logging 'this.id' to see its value.

Answer №2

One reason for this issue is that overwriting values in an array does not trigger reactivity in Vue. As a result, Vue may not detect the change and fail to call your computed property. To tackle this problem, you can try the following approach:

this.records.splice(0, this.records.length - 1, ...response.data)

If you want to delve deeper into this topic, check out the following link: Reactivity in Depth

.splice will work as expected because Vue encapsulates this method and performs necessary operations internally.

Edit 1

for(let i = 0; i < response.data - 1; i++) {
  Vue.set(this.records, i, response.data[i]);
}

Edit 2

After discussing in our chat session, we identified a separate issue related to data types (element ID from the backend being a string while local ID is a number causing .filter to return an empty array). To address this, consider using == instead of ===, or better yet, utilize the following solution:

 record.template_id.toString() === this.id.toString()

This will ensure both IDs are treated as strings for accurate comparison.

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

Customizing Javascript for Mouse Exiting Browser Window

I have implemented a JavaScript function on my website to display a lightbox when the visitor's mouse goes beyond the browser window. You can check it out here: [http://mudchallenger.com/index-test2.html][1] However, there seems to be an issue where ...

Avoid unintended double-tapping on mobile devices

On my main page, I have a button that triggers an overlay with item details, including buttons like one that reveals a phone number. An issue arises when a user accidentally double-clicks the main page button. The first click is processed on the main page ...

Is there a way to eliminate the black seam that is visible on my floor mesh that has been separated? I am utilizing A

I recently imported a large .glb file into AFrame. The model has baked textures and the floor is divided into multiple mesh parts for improved resolution. However, I am facing an issue where black seams appear on the separated parts of the floor, only dis ...

Ways to showcase the contents of a React JavaScript document, or more specifically, a file designed for React interpretation

After trying multiple solutions, I found a conceptual guide on How to call and form a React.js function from HTML. However, the HTML generated doesn't seem to be calling from the JavaScript file as expected. It appears identical to what is mentioned i ...

Refresh the Document Object Model (DOM) and transmit the present time

I am having an issue with sending the actual current time when a button is clicked. Instead of getting the current time, I am receiving the time when the page initially loaded. This button is used to submit a form on Google Sheets using an API. This is th ...

A method for applying the "active" class to the parent element when a child button is clicked, and toggling the "active" class if the button is clicked again

This code is functioning properly with just one small request I have. HTML: <div class="item" ng-repeat="cell in [0,1,2]" data-ng-class="{active:index=='{{$index}}'}"> <button data-ng-click="activate('{{$index}}')">Act ...

How can I transfer information from Node.js to Vue in an Nuxt.js server-side rendering setup?

I need to find a way to pass Firestore data to Vue files from Node.js (Express) because I have to utilize Firestore's getCollections() method, which cannot be executed on the client side. I have set up nuxt-ssr for deploying Google Cloud Functions an ...

Is it possible to use the googleapis npm package to make a query to a googleSheet?

I have a huge dataset with thousands of rows and I want to optimize my queries instead of fetching all the data every time. I checked out the Query language but it doesn't quite fit my needs. For authentication, I am using a Service account: const au ...

Identify unique MongoDb instances within an array of data

My list contains various unique items - search = alluk.distinct('Object of search') I am interested in counting each item individually. Presently, I am counting them manually in the following way - alluk.find({'Object of search':&ap ...

I possess a variety of poppers and desire for the opened one to close when another one is opened

Having built a component that generates 6 unique experiences, each with its own popper containing images, I am struggling to figure out how to modify my code so that one popper closes when another is clicked. Here is the current setup: This is the compone ...

Programming with a combination of Javascript, Angular, and Prototype to efficiently manage and

I am in a bit of a quandary, as I wish to create a function that will clear all the properties of an object and make it available to all instances of that object. To achieve this, I have added a prototype function called clear(). Here is the code snippet: ...

Using the <script> attribute within the <head> tag without the async or defer attributes

https://i.stack.imgur.com/cRFaR.pngCurious about Reddit's use of the async or defer attribute in the script tag. Are there situations where blocking the parser is necessary? ...

Learn how to dynamically switch the background image of a webpage using a button in AngularJS

Hey there, I'm currently working on incorporating interactive buttons into my website to give users the ability to customize the background. I've been experimenting with Angular to achieve this feature. So far, I've managed to change the ba ...

What is the best way to iterate through an object and display each item as <li></li> within another <li>?

After retrieving a specific object from an express endpoint and seeing it on the console, I need to figure out how to map it in order to display a jsx that resembles this <li>keys</li> : <li>values</li> For example: Company: DML ...

Issues with passing Angular directive attributes to the scope were encountered

I am having an issue with my angular directives where the arguments are not being passed into the scope: app.directive('sectionLeft', function() { return { restrict:'E', scope: { sectionContent: '=', s ...

Adding an external CSS file to your .scss files with webpack: A step-by-step guide

Currently, I am working on a JavaScript application that I am compiling using Webpack. The application is split into two separate bundles - one for the custom code called App and another for the frameworks called Vendor. The App bundle consists of all the ...

How can I submit multiple dropdown menus when they are changed?

I recently added Four dropdown menus on my index.php page. <select name="filter_month" class="filters"> <option>Select a Month</option> <option value="1">January</option> <option value="2">February</optio ...

Adding event listeners for elements inside slots in Vue.js: A step-by-step guide

I need to create a unique vue component called "characters-counter" that can accurately count the characters in input elements, as shown below: <characters-counter v-slot =" {charactersCount} "> <div>{{ charactersCount }} Chars< ...

:Incorporating active hyperlinks through javascript

Hey there, I've encountered a little conundrum. I have a header.php file that contains all the header information - navigation and logo. It's super convenient because I can include this file on all my pages where needed, making editing a breeze. ...

Can anyone tell me how to retrieve the value of {{org}} in this situation?

<head> <title>My Unique Page</title> </head> <body> <input type="text" ng-model="selectedOrg" ng-show="!isSuperAdmin" readonly /> <select id="nameOrg" ng-model="selectedOrg" ng-cha ...