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.