Reputation: 373
I have in my store the following:
import Vuex from 'vuex'
import Vue from 'vue'
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
campaigns: '',
currentCampaign: null
},
mutations: {
GET_CAMPAIGNS(state, campaigns) {
state.campaigns = campaigns
}
},
actions: {
getCampaigns ( context ) {
return axios
.get('/api/campaign/history')
.then((response) => {
context.commit('GET_CAMPAIGNS', response.data)
})
},
}
});
The issue is that the campaigns
is still empty. Please, what I'm not doing right?
In my component methods, I called the mutations like so:
markAsCurrent (campaign) {
this.$store.commit('CURRENT_CAMPAIGN', campaign.id)
}
but the currentCampaign
state is returning undefined
Upvotes: 0
Views: 2090
Reputation: 3756
Since you are using actions
and not mutations
to retrieve your data, you should be using the dispatch()
function rather than the commit()
function.
Actually, I would rather you to call the axios.get()
from your methods
than from the store
itself.
markAsCurrent (campaign) {
let campaigns
axios.get('/api/campaign/history').then(response => {
campaigns = response.data
}
this.$store.dispatch('getCampaigns', campaigns)
}
actions: {
getCampaigns ({commit}, campaigns) {
commit('GET_CAMPAIGNS', campaigns)
}
}
Upvotes: 1
Reputation: 27719
Change your actions into the below code:
getCampaigns ( {commit}, context ) {
axios.get('/api/campaign/history')
.then((response) => {
context.commit('GET_CAMPAIGNS', response.data)
})
}
Then you have to call this actions from you component like this:
this.$store.dispatch('getCampaigns', passTheDataHere)
Note: if you want to commit a mutation inside actions you have to use {commit} in arguments.If also you want to use state or getters then {commit,getters,state}
Upvotes: 0