Reputation: 4642
I'm getting used to Vuex
as I need to be able to have a store that I can easily access and update when another component is changed.
Currently, my store
looks like the following:
import vue from 'vue';
import Vuex from 'vuex';
vue.use(Vuex);
export default new Vuex.Store({
state: {
users: {
columns: [],
model: [],
}
},
mutations: {
fetchUsers: function(state) {
axios.get(`/users?search_input=`)
.then(function(response) {
});
}
}
});
The columns
and model
is dynamically pulled down from an ajax request and my Users
looks like the following:
<script>
export default {
mounted() {
this.$store.commit('fetchUsers');
},
computed: {
columns() {
return this.$store.state.users.columns;
}
model() {
return this.$store.state.users.model
}
},
}
</script>
My problem is that the application needs to have data preloaded from Ajax. For example columns
are set from an ajax request in fetchUsers
and inside the Users
I use this.$store.commit('fetchUsers');
but is there an alternative way I can do that without using commit
preferably inside the store itself?
Upvotes: 0
Views: 2106
Reputation: 1727
In the store u can load ur data asynchronously via actions then commit the changes using a mutation.
import vue from 'vue';
import Vuex from 'vuex';
vue.use(Vuex);
export default new Vuex.Store({
state: {
users: {
columns: [],
model: [],
}
},
actions: {
fetchUsers: function( context ) {
axios.get(`/users?search_input=`)
.then( function( response ) {
context.commit( "FETCHUSERS", {
columns: response.columns,
model: response.model
});
});
}
}
mutations: {
FETCHUSERS: function( state, payload ) {
state.users.columns = payload.columns;
state.users.model = payload.model;
}
}
});
Dispatch the action from the component
<script>
export default {
.....
methods: {
fetchUsers: function() {
this.$store.dispatch( "fetchUsers" );
}
}
}
</script>
Upvotes: 4
Reputation: 18126
Mutations must be synchronous: https://vuex.vuejs.org/en/mutations.html
You should move ajax request into actions
, which can be async. You get data in the action
, commit mutation giving received data as a payload, and mutation assigns a value to the state property.
Alternatively, you can make async request in component method, and assign a value to the store property directly: this.$store.state.prop = value
Upvotes: 1