Vuex's commit method will only commit the final value of an array retrieved from a response

Currently, I am encountering a challenge while working on my Laravel vue.js project with vuex. The issue arises when trying to commit a response to the store. Despite successfully fetching array data from the backend, only the last value of the array is being mapped to state upon committing the response. As a result, incorrect results are displayed during iteration. Interestingly, managing the state locally within the component produces the correct outcome. Below is a snippet of the sample response obtained in the console window:

[{…}]
0: {id: 4, auth_id: 3, user_id: 3, power_id: 3, created_at: "2019-01-19 
12:49:15", …}
length: 1
__proto__: Array(0)
app.js:90087 

(2) [{…}, {…}]
0: {id: 1, auth_id: 2, user_id: 2, power_id: 1, created_at: "2019-01-19 
12:03:52", …}
1: {id: 5, auth_id: 3, user_id: 2, power_id: 1, created_at: "2019-01-19 
12:50:02", …}
length: 2
__proto__: Array(0)
app.js:90087 

[{…}]
0: {id: 2, auth_id: 2, user_id: 2, power_id: 2, created_at: "2019-01-19 
12:06:55", …}
length: 1
__proto__: Array(0)
app.js:90087 

(2) [{…}, {…}]
0: {id: 3, auth_id: 3, user_id: 3, power_id: 2, created_at: "2019-01-19 
12:46:48", …}
1: {id: 6, auth_id: 3, user_id: 3, power_id: 2, created_at: "2019-01-19 
12:50:22", …}
length: 2
__proto__: Array(0)

Here is how I am retrieving and committing the data:

fetchVotes() {
  axios.get('/api/superpowers/fetchVotes/' + this.powerId + '/' +
      this.userId)
    .then(response => {
      console.log(response.data);
      this.$store.commit('fetchVotes', response.data);
    })
    .catch(error => { console.log(error) });
},

However, after using the store mutation function as shown below, only the last element of the array gets assigned to the state 'votes':

fetchVotes(state, payload) {
  state.votes = payload
},

In contrast, when handling the state locally in the following manner, the functionality works correctly:

 fetchVotes() {
   axios.get('/api/superpowers/fetchVotes/' + this.powerId + '/' +
       this.userId)
     .then(response => {
       console.log(response.data);
       this.votes = response.data
     })
     .catch(error => { console.log(error) })
 },

Please bear in mind that the fetchVotes method is invoked within a forEach loop. Any assistance provided will be highly appreciated.

Answer №1

https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats

Vuex, being a plugin of Vue, adheres to the same reactivity rules as reactive properties in Vue. When dealing with an array of objects, Vue will only detect changes in the size of the array, not the details of each item within it. To ensure that updates are properly triggered in the view layer, you should use Vue.set:

import Vue from 'vue'

...

fetchVotes(state, payload) {
  Vue.set(state, 'votes', payload)
},

If you need to delete items from your array, utilize Vue.delete instead of regular delete.

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

I keep encountering an error when sending a request to the express HTTP server

I have recently started learning node.js and I am trying to figure out how to call a java program from node.js and then send the data back to the client. _http_outgoing.js:636 nextTick(msg.socket[async_id_symbol], ^ TypeError: Cannot r ...

Updating the contents of a list with new additions and removals

Struggling with a simple issue that I just can't seem to find a solution for. My problem involves a list based on 5 checkboxes. abc.html <li id="DisplaySelection"> </li> {{form.Test1 }} //checkbox1 .... {{form.Test5 }} //checkbox5 ma ...

Creating lines in three.js with CanvasRenderer results in more fluid lines compared to WebGLRenderer

I'm facing a dilemma involving three.js where the CanvasRenderer renders lines much smoother than the WebGLRenderer. It seems like there is no antialiasing applied by the WebGLRenderer. When I refer to the three.js canvas - lines - random example fro ...

Utilizing EsLint with the airbnb-base configuration to ensure no unresolved imports in

I recently created a project using Vue-cli and decided to include a lint configuration by default. However, I am encountering an issue when running the lint command: error: Unable to resolve path to module '@/components/HelloWorld.vue' (import ...

JavaScript Bridge function in WebView not invoked

I encountered a strange issue with my application, which functions as an e-reader. To invoke functions for the web view, I utilize a JavaScript class: public class MyJavaScriptInterface { Context mContext; /* Instantiate the interface ...

What is the process for translating or shifting a numpy array?

Can someone help me figure out the right keyword to search for? I want to shift the non-zero entries of a numpy array in a fixed direction. Here's an example with a 2D array: 0 1 2 0 0 3 0 0 0 0 0 0 0 0 0 0 If we shift it by (1,1), the resulting arr ...

Displaying an array using Javascript that contains variables along with HTML code

First of all, thank you for your help and support! I am struggling with correctly outputting HTML code with variables using jQuery and jQuery Mobile. I receive results from a PHP database, separated by "," and converted into a JavaScript array successfull ...

How to form an array using rxjs before the adding sequence is completed

I am currently exploring a way to utilize rxjs to achieve the following scenario: You have two observables, onAddObs and onRemoveObs. Assume that onAddObs.next() is triggered multiple times, adding "A", "B", "C". I aim to then extract ["A", "B", "C"]. .t ...

What is the reason for the neglect of this function's definition?

Is there a reason behind the error message I am receiving? TypeError: getStatusCode(...) is not a function This error occurs when I execute the following code: const getStatusCode = require('./getStatusCode') tmpStatus = await getStatusCode({url ...

Despite successfully passing props into V-for, the output does not display the props as expected

I've been attempting to accomplish a straightforward task, but for some reason, it's not working and I can't figure out why. Within the parent component, App.vue, I have the following: data() { return { servers: [ { ...

Ways to transfer HTML page data into a Python variable using a URL

I stumbled upon a helpful guide at: https://docs.python.org/2/library/htmlparser.html However, the HTMLParser.feed(data) function requires data to be actual HTML content. Is there a way to achieve a similar feed but using only a web address? Maybe someth ...

Executing ng-show function in Angular.js after the scope has been updated

I have a survey application, where users can participate in polls by voting for different options. Within the HTML template, I utilize ng-show to display whether a user has voted for a particular option in a poll or if it remains unvoted for the user: < ...

Incorporating the 'active' class into Nuxt.js with Bootstrap

Trying to enhance my Nuxt.js project, I am looking to apply the active class to a specific nav item. Below is the code snippet for my navigation setup: <div> <b-navbar type="dark" variant="dark"> <b-navbar-nav> <b-nav-item ...

Calculating the mean value of a multidimensional array that has been sorted in JavaScript

Check out the structure of my JSON File below. { "questions": ["Question1", "Question2"], "orgs": ["Org1", "Org2", "Org3"], "dates": ["Q1", "Q2", "Q3"], "values": [ [ [5, 88, 18], [50, 83, 10], ...

Using Javascript to segregate JSON object attributes into a fresh array

I have over 100 JSON objects in this specific format: { "grants":[ { "grant":0, "ID": "EP/E027261/1", "Title": "Semiconductor Research at the Materials-Device Interface", "PIID": "6674", "Scheme": "Platform Grants", "StartDate": "0 ...

Combine various 2D numpy arrays to create a single 3D numpy array

I am working on a project where I need to combine multiple 2-D numpy arrays into a single 3-D numpy array and then save it as a compressed file in a specific directory for future use. As I iterate through a list, I compute forecasts for different hazards. ...

Could not complete operation: EPERM error indicating permission denied for 'stat' operation

Recently delving into Firebase Functions for my Flutter project has been a game-changer. Discovering the code generator, firebase_functions_interop, that seamlessly transforms Dart code into Javascript has made developing cloud functions in Dart a breeze. ...

connect validation of the form to a separate component from the current one

Currently, I am working on creating a searchable-dropdown component that I intend to use in multiple components. However, I am facing an issue with binding form validation to this component. For instance, I have a form for creating a user and I need to bi ...

Rotating objects in Three.js: Aligning with a target point and orienting towards another location

I'm a beginner when it comes to three.js and 3d programming, so forgive me if this question sounds basic. I'm hoping for an answer that can help me grasp the core concepts. Currently, I have an object that needs to face another point (in this ca ...

Ways to resolve the error message "unable to find @require file ~vuetify/src/stylus/settings/_colors.styl"

Currently, my project is using Nuxt along with Vuetify version 1.5.6. I have decided to upgrade Vuetify to the latest version, which is 2.0.1. However, upon completing the upgrade, I encountered the following error message: ERROR in ./assets/style/app.styl ...