I have my mutation committed, but the currentCampaign state is not updated instead returns undefined. Below is the screenshot.
This is the store.
import Vuex from 'vuex'
import Vue from 'vue'
import axios from 'axios'
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
campaigns: '',
currentCampaign: ''
},
actions: {
getCampaigns ( {commit} ) {
axios
.get('/api/campaign/history')
.then((response) => {
commit('GET_CAMPAIGNS', {campaigns: response.data});
})
}
},
mutations: {
GET_CAMPAIGNS: (state, {campaigns}) => {
state.campaigns = campaigns
},
getCurrentCampaign (state, {campaign}) {
state.currentCampaign = campaign
}
},
});
I am calling the mutation from component method like so:
methods: {
markAsCurrent (campaign) {
this.$store.commit('getCurrentCampaign', campaign.id)
}
}
What I'm not doing right here?
Thats why you are destructuring a campaign var and passing a number to the mutations, not a object.
Try this
getCurrentCampaign (state, campaign) {
state.currentCampaign = campaign
}
Related
I am trying to delete an item from the cart. So I should be able to delete the item with the id of the cart.
I have a cartHelper and there I defined my api call:
removeFromCart: function (id, callback = undefined) {
return apiHelper.deleteRequest(
`/carts/${this.cookieValue}/remove-item`,
(response) => {
document.cookie = `${this.cartCookieName}=${response.data.attributes.cart_guid};`;
if (callback) { callback(response); }
},
{
id: id
}
)
},
And later I am calling this function in my Cart component:
methods: {
removeFromCart(id) {
cartHelper.removeFromCart(id, () => {
this.$store.dispatch('removeProductFromCart', id)
});
},
},
And I defined my action like in the below:
export const removeProductFromCart = ({ commit }, id) => {
commit('REMOVE_PRODUCT_FROM_CART', id);
}
And here is my mutation:
export const REMOVE_PRODUCT_FROM_CART = (state, id) => {
state.cart = state.cart.filter(item => {
return item.id !== id;
})
}
But as soon as I click the button, where I am calling removeFromCart in my Cart component, I am getting "TypeError: _vm.removeProductFromCart is not a function" and I couldn't figure out the reason. If you can help me, that would be great.
Edited version---------
Here is my state:
export default {
cart: {
"attributes": {
"items": [],
}
}
And my index.js for store:
import Vue from 'vue';
import Vuex from "vuex";
Vue.use(Vuex);
import state from "./state";
import * as getters from './getters';
import * as mutations from "./mutations";
import * as actions from "./actions";
export default new Vuex.Store({
state,
getters,
mutations,
actions,
});
}
Seems you have been calling removeProductFromCart on #click event which does not exist in you methods. Try calling removeFromCart on #click event.
Creating a Vuejs application whereby I use Vuex for state management between the components.In Vuex store, I have an action that fetches some data from an API (which works fine) then populate it to the state (via a mutation). Next, I pass the updated state to the component using getters.
Am having a problem populating data to the state (reactive manner) from the action (via mutation). In the DOM when I log the getter am getting an empty string.
Vuex Store
const getDefaultState = () => {
return {
clientDeposit: ''
}
}
//state
const state = getDefaultState();
//getters
const getters = {
getDeposit: (state) => state.clientDeposit
}
//actions
const actions = {
fetchClients({ commit}) {
const clientId ="23"
axios.post('/api/motor/fetchClients', {
ClientId: clientId,
})
.then((response)=> {
//console.log(response); //returns data
const deposit = response.data;
commit('setDeposit', deposit);
})
}
}
//mutations
const mutations = {
setDeposit: (state, value) => (state.clientDeposit = value)
}
export default {
state,
getters,
actions,
mutations
}
Component
<template>
<div>
<button onclick="fetchClients()">Fetch Clients</button>
Deposit (Via computed property) : {{ fetchDeposit }}
Deposit (from getter) : {{ getDeposit }}
</div>
</template>
<script>
import { mapGetters , mapActions } from "vuex";
import axios from "axios";
export default {
name: "",
data() {
return {
}
},
computed: {
...mapGetters([
"getDeposit"
]),
fetchDeposit(){
return this.getDeposit
},
},
methods:{
...mapActions([
"fetchClients"
])
}
};
</script>
<style scoped>
</style>
I'm able to console data, as well as able to see data in vuex dev tool
but not able to display them in table. Please if someone could check
my code and tell me what is wrong with it. Thanks folks. I tried differents methods like async/await, promise, getters... but I was not able to to get the data, probably I was not calling it properly.
ROLE.VUE
<emplate>
<di>
<p v-for="(role, index) in roles :key="index">
</div>
</template>
<script>
import { mapState } from 'vuex'
export default ({
name: 'Role',
metaInfo: {
title: 'Role'
},
created () {
this.$store.dispatch('loadRoles').then((response) => { console.log(response) })
},
computed: {
...mapState([
'roles'
])
}
})
</script>
role.js
import Axios from 'axios'
export default {
// namespaced: true,
state: {
roles: [],
},
getters: {
roles (state) {
return state.roles
}
},
mutations: {
SET_ROLES (state, roles) {
state.roles = roles
}
},
actions: {
loadRoles ({ commit }) {
Axios.get('/settings/roles')
.then((response) => {
console.log(response.data)
// let roles = response.data
commit('SET_ROLES', response.data.roles)
})
}
}
}
index.js
import role from './role'
Vue.use(Vuex)
export const store = new Vuex.Store({
state: {
},
mutations: {
//
},
modules: {
role
},
actions: {
//
}
})
Main.js
import { store } from './store/store'
new Vue({
router,
store,
ValidationProvider,
render: h => h(App)
})
When loading from a module with mapState, you need to specify the name of the module you are loading from. Here is the proper syntax for your case:
...mapState('role', ['roles'])
The first argument is the module name, and the second is an array of state properties from that module.
I am new to Vuex and trying to use mapActions to fetch some data from my store, and send it into my component's template. I keep getting the error message
[vuex] unknown action type: getItemDetail but I don't know why.
In my store, the action I'm trying to dispatch is getItemDetail. My full store is
import fetch from './fetch';
const url = 'items';
const defaults = {
id: '',
rating: '',
type: '',
};
const state = { ...defaults, };
const getters = {};
const actions = {
getItemDetail ({ commit, }, itemId) {
fetch.get(`${url}/${itemId}`).then((response) => {
commit('setItemDetail', { ...defaults, ...response.data, });
});
},
};
const mutations = {
setItemDetail (state, item) {
state.item = item;
},
};
export default {
namespaced: true,
state,
getters,
actions,
mutations,
};
In my component I have:
<template>
<div>
<p> {{ itemDetail }} </p>
</div>
</template>
<script>
import { mapActions } from 'vuex';
export default {
computed: {
itemDetail () {
this.getItemDetail('23451');
return this.$store.state;
},
},
methods: {
...mapActions([
'getItemDetail',
]),
},
};
</script>
Any help would be much appreciated!!!
From what I see of your code, you are in a namespaced store module.
To access a namespaced action, you need to map it with the name of the store module as the first parameter (the same should be applied for any mapState or mapGetter) :
methods: {
...mapActions("yourModuleName", [
'getItemDetail',
]),
},
I've been using nuxtServerInit to fetch data from my contenful CMS and commit the mutation to add the data to the categories state object. However categories keeps showing empty, even when I try to render it on a component.
I can console.log the data in the mutation function and see the data, why isn't it being pushed into the categories state?
import Vuex from 'vuex'
import {createClient} from '~/plugins/contentful.js' //contentful plugin function
const client = createClient()
const createStore = () => {
return new Vuex.Store({
state: {
categories: {}
},
mutations: {
addCategories(state, data) {
state.categories += data.items
}
},
actions: {
async nuxtServerInit(context) {
client.getEntries({
content_type: 'category' //fetch everything with the content type set to category
})
.then(response => context.commit('addCategories', response))
.catch(console.error)
}
},
})
}
export default createStore
import Vue from 'vue'
import Vuex from 'vuex'
import { createClient } from '~/plugins/contentful'
const client = createClient()
export default = () => new Vuex.Store({
state: {
categories: {}
},
mutations: {
addCategories (state, data) {
Vue.$set(state, 'categories', [...data.items, ...state.catagories])
},
},
actions: {
async nuxtServerInit ({ commit }) {
let response
try {
response = await client.getEntries({ content_type: 'category' })
}
catch (error) {
console.log(error)
}
context.commit('addCategories', response)
},
})