Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
109
rated 0 times [  113] [ 4]  / answers: 1 / hits: 77948  / 7 Years ago, tue, january 24, 2017, 12:00:00

I'm using Vuex to show a list of users from 'store.js'. That js file has array like this.



var store = new Vuex.Store({
state: {
customers: [
{ id: '1', name: 'user 1',},
]
}
})


I want to insert a new set of values to the same array




{ id: '1', name: 'user 1',}




The above values are obtained from a URL (vue-resource). Below is the code to push the obtained data to the array. However, the data is not inserting



mounted: function() {
this.$http.get('http://localhost/facebook-login/api/get_customers.php')
.then(response => {
return response.data;
})
.then(data => {
store.state.customers.push(data) // not working!!
console.log(data) // prints { id: '2', name: 'User 2',}
store.state.customers.push({ id: '2', name: 'User 2',})
});
}

More From » arrays

 Answers
15

You are trying to modify the vuex state from the vue component, You can not do it. You can only modify vuex store from a mutation



You can define a mutation like following:



var store = new Vuex.Store({
state: {
customers: [
{ id: '1', name: 'user 1',},
]
},
mutations: {
addCustomer (state, customer) {
// mutate state
state.customers.push(customer)
}
}
})


Now you can commit this mutation from the vue instance, like following:



mounted: function() {
this.$http.get('http://localhost/facebook-login/api/get_customers.php')
.then(response => {
return response.data;
})
.then(data => {
store.commit('addCustomer', { id: '2', name: 'User 2'})
});
}

[#59227] Sunday, January 22, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elainaw

Total Points: 83
Total Questions: 99
Total Answers: 111

Location: South Sudan
Member since Sat, May 27, 2023
1 Year ago
;