Vue: The computed property cannot be set

I'm having trouble with utilizing computed properties and ajax calls in Vue.js.

The "filterFactories" variable stores a list of factories. A computed property named "filterFactories" generates this list of factories.

Now, I am looking to implement a new functionality: There is a button that triggers an ajax request to fetch additional factories. I want to update the computed property "filterFactories" after the ajax request is successful. However, the update does not happen as expected. Neither of the following methods make any difference: 1. Setting this.filterFactories = response; 2. Setting window.filterFactories = response; Both approaches do not update the property.

Is there a way to refresh the "filterFactories" variable after a successful ajax call?

The following is a snippet of the larger code I'm working with:

<!-- Add your code snippet here -->

Answer №1

When working with Vue, computed properties can sometimes feel like magic. Vue scans the function code and automatically creates watchers for the properties it detects within the code. While this approach is effective in simpler scenarios, it can fall short when dealing with loops, map, reduce, and so on.

To address this issue, I have developed several workarounds, but one of the simplest and most straightforward methods involves creating an artificial property that you reference in the computed property and then update as necessary:

new Vue({
    data: {
        updated: 0,
    },
    computed: {
        myComputed(): {
            // ...
            // simply reference the artificial property
            this.updated;
        },
    },
    methods: {
        myAjax(): {
            // ...
            // modifying the artificial property triggers an update of myComputed
            this.updated++;
        },
    },
});

It's important to choose names that accurately reflect the specific use cases you're dealing with, although I've found instances where simply naming this property "updateDummy" suffices ;)

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

Unable to assign a value to the HTMLInputElement's property: The input field can only be set to a filename or an empty string programmatically

When attempting to upload an image, I encountered the error message listed in the question title: This is my template <input type="file" formControlName="avatar" accept=".jpg, .jpeg .svg" #fileInput (change)="uploa ...

Utilizing Promise.all() for handling multiple promises with multiple arguments

Currently, I am dynamically constructing a list of entries utilizing data retrieved from the server. Each entry is associated with a parent. My objective is to extract the parent's name from the DOM by locating its ID. This process works effectively ...

Steps to selectively enable or disable checkboxes in a dynamic table depending on a dropdown selection

I'm currently facing an issue with a dynamically generated HTML table from a JSON file. Each row in the table consists of a dropdown list and a checkbox. I need the checkbox to be disabled when the default value is selected in the dropdown, and enable ...

Using Vue.js for instant field validation when sending PHP post forms for enhanced user experience

A unique approach is being taken to utilize vue.js exclusively for real-time field validation, while the form will ultimately be submitted using PHP through the POST method. However, a challenge arises where vue.js takes control of the form, hindering PHP& ...

Tips for ensuring an element stays anchored at the bottom even when the keyboard is displayed

I recently encountered a situation on one of my pages where an element positioned at the bottom using absolute positioning was causing issues when the keyboard was opened, as it would move to the middle of the page unexpectedly. While this may seem like a ...

The PDFKIT feature ensures that any overflowing data in a row is automatically moved to a new page

A function in my code generates a row of data based on an array. It works perfectly fine for the first page, but as soon as the data overflows somewhere around doc.text("example",70,560), it jumps to the next page. The issue arises when the Y coo ...

A guide to showcasing data within PrimeNG's pie chart component using either JavaScript or Angular

I have utilized the pie chart feature from the PRIMENG CHART PLUGIN My goal is to showcase the values within a pie chart Below, you can find my code for reference **Within app.component.html** <div style="display: block"> <p-chart type="pi ...

Is there a way to achieve a similar effect to "object-fit: cover" for CylinderGeometry in three.js while utilizing THREE.VideoTexture()?

I'm really interested in creating something similar to this: https://i.sstatic.net/mWuDM.png Imagine the checkered background as a texture, and I want the jar to be a cylinder with that texture applied to it. My knowledge of three.js is limited, so ...

Issue with jQuery .hover() not functioning as expected

The issue I'm encountering is just as described in the title. The code functions correctly on all divs except for one! $(".complete-wrapper-1").hide(); var panelHH = $(".file-select-wrapper").innerHeight; $(".files-button").hover(function(){ $(" ...

Displaying the content of the log file within a textarea

Currently, I am working on a project that involves displaying log file contents in a text area. To achieve this, I am utilizing XML HTTP request to read the file content through a Web API. The Web API function reads the file contents as a stream and retu ...

Modify the NAME attribute when clicked using Jquery

I am attempting to modify the NAME attribute of a DIV with the text from a textbox using jQuery. Take a look at my code snippet: http://jsfiddle.net/e6kCH/ Can anyone help me troubleshoot this issue? ...

Interactive Div Updates Dropdown Selections Automatically

// function to add set of elements var ed = 1; function new_server() { ed++; var newDiv = $('#server div:first').clone(); newDiv.attr('id', ed); var delLink = '<a class="btn btn-danger" style="text-align:right;m ...

The JQqplot graph is failing to display correctly following an ajaxpost operation

When drawing a chart in two different scenarios, the first scenario is during the onload event and the second one is after the successful completion of an ajax post. The same code is being called in both scenarios. During the onload function, the chart l ...

`Upkeeping service variable upon route alteration in Angular 2`

Utilizing a UI service to control the styling of elements on my webpage is essential. The members of this service change with each route, determining how the header and page will look. For example: If the headerStyle member of the service is set to dark ...

How can I automatically update the preview image on a website shared on Facebook?

I tried the code below, but it doesn't seem to be working. Is it possible to dynamically achieve this? If yes, how can I do it? I initially used the og:image meta tag, but it didn't work due to browsers not reading JavaScript. Any assistance woul ...

I'm encountering an unfamiliar plugin type in Nuxt 3

Within my Nuxt 3 application, I have developed a custom plugin located in the plugins/ folder. // plugins/customPlugin.ts export default defineNuxtPlugin(() => ({ provide: { hello: (msg: string) => console.log(`This is your message: ${msg}` ...

Refreshing Angular Services: A Guide to Resetting Factories

My angular factory is quite intricate and structured like this: app.factory("mainFcty", function(){ return { a:"", b:"", c:"" } }); When users progress through the app and complete actions such as booking a service, they f ...

What is the best way to choose the nearest element using the initial part of a class name?

I am working on a section of a table and need to hide a specific part when an icon is clicked. Below is the code snippet: <tr class="getmoreinfo_19"> <td>&nbsp;</td> <td colspan="3"> <div c ...

Node.js Binary Search Tree - Error: Identifier Not Found

A program run through node.js has been developed to create a binary search tree with various methods like insert, remove, and print. The program is divided into two separate files: Tree.js, which exports the functions Tree() along with its methods and test ...

Is it necessary to include a promise in the test when utilizing Chai as Promised?

Documentation provided by Chai as Promised indicates the following: Note: when using promise assertions, either return the promise or notify(done) must be used. Examples from the site demonstrate this concept: return doSomethingAsync().should.eventua ...