"Vue's watch method seems to be failing to properly filter through

The filter functionality within a Vue watched function doesn't appear to be functioning as expected. Despite returning false for the E: object and true for all other items, the E: object remains in the array when it should have been removed.

Below is the object passed to the component via prop:

[
    {
        "fs": "C:",
        "type": "NTFS",
        "size": 273649844224,
        "used": 265129050112,
        "use": 96.88624192856284,
        "mount": "C:"
    },
    {
        "fs": "D:",
        "type": "NTFS",
        "size": 1000202039296,
        "used": 879919800320,
        "use": 87.97420578539696,
        "mount": "D:"
    },
    {
        "fs": "E:",
        "type": "NTFS",
        "size": 524283904,
        "used": 35745792,
        "use": 6.818022015796998,
        "mount": "E:"
    },
    {
        "fs": "F:",
        "type": "NTFS",
        "size": 250058108928,
        "used": 193818132480,
        "use": 77.50923707729336,
        "mount": "F:"
    },
    {
        "fs": "G:",
        "type": "NTFS",
        "size": 249464614912,
        "used": 149687517184,
        "use": 60.00350680468374,
        "mount": "G:"
    }
]

Component Script:

export default {
  name: "DISK",
  props: ["diskinfo"],
  watch: {
    diskinfo: function () {
      if (typeof this.diskinfo !== "undefined") {
        // convert to GB
        this.diskinfo.forEach((disk) => {
          disk.used = (disk.used / 1073741824).toFixed(0);
          disk.size = (disk.size / 1073741824).toFixed(0);
        });
        // remove if < 1 gb
        this.diskinfo.filter((disk) => disk.size === "0"); //πŸ‘„πŸ‘„πŸ‘„ Not filtering
      }
    },
  },
};

Answer β„–1

  1. It is not recommended to alter a prop value, as this goes against Vue best practices
  2. Array.prototype.filter() focuses on determining what data to keep, rather than what to discard. If you want to eliminate elements with size === 0, use a comparison like size > 0
  3. If you do not utilize the output of Array.prototype.filter(), any modifications will not be saved

The handling of the diskinfo prop within this component is unclear, but a common approach for such scenarios is employing a computed property

export default {
  name: "DISK",
  props: { diskinfo: Array },
  computed: {
    formattedDiskInfo () {
      return this.diskinfo.map(di => ({
        ...di,
        used: (di.used / 1073741824).toFixed(0),
        size: (di.size / 1073741824).toFixed(0)
      })).filter(({ size }) => size > 0)
    }
  }
}

In your template, consider using the formattedDiskInfo array instead of directly relying on the diskinfo prop.

Answer β„–2

When using the filter method, a new array is returned with the filtered results:

a = [1,2,3]

a.filter((b) => b < 2) // This will return [1], but the original array 'a' remains as [1,2,3]

For example:

this.diskinfo = this.diskinfo.filter((disk) => disk.size === "0")

Answer β„–3

According to Phill and Cyrbuzz, the filter function will give you a filtered array as output, which means you need to make the following adjustment:

Instead of: this.diskinfo.filter((disk) => disk.size === "0");

Do this instead:

Update it to: this.diskinfo = this.diskinfo.filter((disk) => disk.size === "0");

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

Utilizing modular structure for efficient jQuery AJAX request

Seeking guidance on optimizing multiple GET ajax calls, where each function contains repeated $.ajax({}) code lines. Is it feasible to create a single $.ajax({}) function and utilize it in all functions instead of duplicating the code? Perhaps something ...

Is it possible to smoothly transition from one background image to another in CSS or JavaScript?

Most tutorials I've come across suggest using a background image with a linear gradient overlay, but that solution doesn't suit my needs: I have two adjacent divs with background images, slightly overlapping by 50px. I wish to create a gradient ...

Attempting to implement a basic AngularJS integration with Google Maps for a straightforward demonstration

I have a basic Google Maps project that I am trying to transition into an AngularJS project. This is all new to me as I am a beginner in both AngularJS and web development so please bear with me :) The project can be found at https://github.com/eroth/angul ...

Make sure the variable is present in the store state by utilizing vuex

My application only loads to the DOM if user details are available: <template> <div id="app"> <template v-if="loggedUser"> //... </template> </div> </template> The loggedUser property is a computed valu ...

Issue with CKEditor5 Link popup not displaying in both Bootstrap 5 modal and RSuite library modal in React

React: How to troubleshoot CKEditor5 Link popup not appearing in a modal using either Bootstrap 5 or rsuite library? Seeking advice on resolving this issue. Your help is appreciated! ...

Implementing React with multiple event listeners for a single click event

One of the challenges I'm facing is with a function called playerJoin() in my React app. This function is triggered when a specific button is clicked. It sends data to the server, which then checks if the information matches what is stored. If there i ...

Creating an image on an HTML canvas using RGB values

Looking for assistance on displaying an image using HTML Canvas with three 12x12 arrays containing R, G, and B values. I've seen Canvas demos showing how to draw lines, but nothing on using RGB arrays to create an image. Any tips or guidance would be ...

Choose or unselect checkboxes that are currently visible

I am working on an accordion feature that includes checkboxes for each item. Some of the accordion items are initially hidden using the style="display:none;" attribute. Take a look at the HTML DOM hierarchy in this screenshot: https://i.sstatic.net/Za8Ly ...

Display/Collapse SELECT choices?

Consider this scenario : <select class="form-control" name="blah" ng-model="$ctrl.form.blah" ng-options="item.id as item.name group by item.etype | uppercase for item in $ctrl.opts"></select> My goal is to toggle the display of each GROUP b ...

I am a newcomer to HTML and I am eager to display the selected options from a <select> element

Can someone help me display the selected licorice flavor, chocolate color, and topping? For example: "Green apple, white, christmas sprinkles." I'm not sure if assigning a numeric value to each option is necessary. I did it on a whim. Please suggest ...

A guide on how to activate an event when a radio button is selected using jQuery

I experimented with implementing this. When I try clicking on the radio button, the code functions correctly, but the radio button does not appear to be checked and remains unchanged. Any ideas on how to resolve this issue? <p> <input id="p ...

Preserving the jQuery object during an AJAX postζ“δ½œ

When using AJAX calls, I am looking to preserve the datatable object. See the code snippet below: $(function(){ function applyDataTables(options) { //datatable object var $datatable = $("#table1").dataTable(options); ...

Is there a way to modify the appearance of a particular element in ng-repeat?

On my website, I am using ng-repeat to display various dish postings. I want to trigger a modal to open when I click on a dish, showing the specific data for that dish. To achieve this, I'm assigning each dish a modal div with a unique ID (dish-$index ...

Error encountered with the Angular 2 routing system

Currently, I am facing an issue with my Angular 2 router module. Whenever I try to access the link /city, I encounter an error message saying 'ERROR Error: Uncaught (in promise): Error: Cannot activate an already activated outlet Error: Cannot activat ...

Trying to decide between using a Javascript or HTML5 PDF Editor?

I am in need of a solution that enables users to edit PDF files directly on an ASP.NET web page. This functionality is intended for creating templates and adding blocks/form fields to existing PDFs, complete with rulers and other necessary features. Desp ...

Cloning a checkbox using Jquery

I am working on a search page that utilizes checkboxes to display results. After the user selects certain options and triggers a reload of the page, I want to provide an easy way for them to remove their selections by displaying them at the top of the page ...

Update the background's color by cycling through a set of colors stored in

I have a container on my webpage with a light blue background, and I want the background color to darken progressively with each click. Currently, I am manually setting an array of colors for this purpose, but I am struggling to make the background color c ...

Incorporated asynchronous functionality, struggling to integrate it into the code

Previously, I used to utilize the following code for handling state: //get state MyClass.prototype.getState = function(key) { var value; switch(this._options.type){ case "cookie": value = $.cookie(key); ...

Is there a way to retrieve Google Scholar citations using SERPAPI?

I am looking to retrieve citations for a list of authors along with their email IDs. Is there a way to programmatically fetch these citations using SERPAPI? ...

Error: The import statement is invalid when used outside of a module

Click here to watch the video <!DOCTYPE html> <html> <head> <title>Three.js</title> <style type="text/css> html, body {margin: 0; padding: 0; overflow: hidden} </style> </head> <body> <div id="w ...