this.$store.dispatch works but ...mapActions does not - vue.js

Using vue 2 I'm trying to initialize data in vuex from a component before it loads. I can use the this.$store.dispatch and the action, along with its subsequent mutation, will run as expected from the created() function. If I call the same method in the created() function on the component using ...mapActions, the action and mutation in the module in the vuex store do not run as expected. I've looked at various ways to do this with namespacing the module (as it isn't the only module in this program), but I can't seem to get the method to run. It may be a timing in the lifecycle issue, but I'm not sure why created() wouldn't be appropriate. The addStage method is what I'm trying to have run to create the data in vuex to be displayed once the component that needs the data is loaded.
In a separate component (not shown here) I can use the ...mapActions helper by firing it from a button #click and it runs the addStage method from vuex just fine. What am I missing?
Component:
<template>
<div v-for="stage in getFlow.stages" :key="stage.id">
<flowstage v-for="step in stage.steps" :key="step.id">
<flowstep></flowstep>
</flowstage>
</div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex';
export default {
name: 'flowbuildersub',
created(){
this.addStage;
//this.$store.dispatch('flowbuilder/addStage');
console.log("added stage");
},
methods: {
...mapActions('flowbuilder', ['addStage']),
},
computed: {
...mapGetters('flowbuilder', ['getFlow']),
}
}
</script>
Store:
import Vue from 'vue';
import Vuex from 'vuex';
import flowbuilder from './modules/flowbuilder.js';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
error: null,
loading: false,
information: null
},
getters: {
getError(state) {
return state.error;
},
getInformation(state) {
return state.information;
},
getLoading(state) {
return state.loading;
},
},
mutations: {
setInformation(state, payload) {
state.information = payload
},
setError(state, payload) {
state.error = payload
},
setLoading(state, payload) {
state.loading = payload
}
},
modules: {
flowbuilder
}
})
flowbuilder.js module:
export const state = {
flow: {
id: Math.ceil(Math.random()*100000000)+Math.floor(Date.now() / 1000),
name: null,
description: null,
modifiedBy: null,
stages: [],
},
};
export const getters = {
getFlow(state) {
return state.flow;
},
getStages(state) {
return state.flow.stages;
},
};
export const actions = {
addStage({ commit }) {
let defaultStep = {
id: 1,
type: "Assign",
data: null,
description: null,
subStep: null,
required: null,
selected: true,
};
let defaultStage = {
id: 1,
label: null,
description: null,
selected: false,
steps: [
defaultStep
],
};
console.log("made it here");
commit('ADDSTAGE', defaultStage);
},
};
export const mutations = {
ADDSTAGE(state, defaultStage) {
state.flow.stages.push(defaultStage);
console.log("added stage");
},
};
export default {
namespaced: true,
state,
getters,
actions,
mutations
};

Related

Vuex with Nuxt Error: this.$store is undefined

I'm coding along with a Nuxt course and I got the following error while of course it worked in the tutorial.
TypeError: can't access property "dispatch", this.$store is undefined
store/index.js file:
import Vuex from "vuex";
const createStore = () => {
return new Vuex.Store({
state: { loadedPosts: [] },
mutations: {
setPosts(state, posts) {
state.loadedPosts = posts;
},
},
actions: {
setPosts(vuexContext, posts) {
vuexContext.commit("setPosts", posts);
},
},
getters: {
loadedPosts(state) {
console.log("imhere");
return state.loadedPosts;
},
},
});
};
export default createStore;
the script in posts/index.vue file:
<script>
export default {
data() {
return {
loadedPosts: [{id: "1",title: "First Post"}],
};
},
created() {
this.$store.dispatch("setPosts", this.loadedPosts);
},
};
</script>

errors: `unknown mutation type: setLoggedIn` & `unknown local mutation type: setLoggedIn, global type: auth/setLoggedIn`

two errors help me build with vuex modules
errors: unknown mutation type: setLoggedIn & unknown local mutation type: setLoggedIn, global type: auth/setLoggedIn
vuex version "vuex": "^4.0.0"
the problem occurs in the setLoggedInState(ctx) function
index.js
import Vuex from 'vuex'
import middleware from "./modules/middleware.js";
import auth from "./modules/auth";
export default new Vuex.Store({
namespaced: true,
modules: {
auth,
middleware
}
})
auth.js
const state = {
isLoggedIn: true,
};
const mutation = {
setLoggedIn(state, payload, ) {
state.isLoggedIn = payload;
},
};
const actions = {
setLoggedInState(ctx) {
return new Promise((resolve) => {
if (localStorage.getItem('token')) {
ctx.commit('setLoggedIn', true, {root: true});
resolve(true)
} else {
ctx.commit('setLoggedIn', false, {root: true});
resolve(false)
}
});
},
}
const getters = {
loggedIn(state) {
return state.isLoggedIn;
},
export default {
namespaced: true,
state,
mutation,
actions,
getters
}
Dashboard
import {mapActions} from 'vuex'
export default {
name: "Dashboard",
data: () => ({}),
created() {
this.checkUserState();
},
methods: {
...mapActions({
checkUserState: 'auth/setLoggedInState',
}),
I don’t understand how to fix errors I tried many ways I hope for your help
When you learn something new, please check for missing '; , .' etc.
And be sure that you write 'const mutations' not 'const mutation', following the documentation saving hours))

vuex unknown action type: events/loadAll

I am hoping someone can help me out. I moved all my modules from the store/index.js file to a new store/events.js files to clean things up. I am having troubles getting the namespace right for the loadAll action from event.js. Not sure what I am missing here as I got followed some documentation and believe this should be right. I included App.js where I am trying to us "this.$store.dispatch('events/loadAll')" to get the loadAll action. You can see the loadCurrent action is also dispatched in similar fashion and works just fine. Any help would be appreciated.
index.js
import Vue from 'vue'
import Vuex from 'vuex'
import snackbarModule from './snackbar';
import eventsModule from './events';
import usersModule from './users';
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
snackbar: snackbarModule,
eventNames: eventsModule,
users: usersModule
}
})
event.js
import Api from "../service/api"
export default {
namespaced: true,
state: {
eventNames: [],
},
mutations: {
SET_EVENTNAMES(state, eventNames) {
state.eventNames = eventNames
}
},
actions: {
async loadAll({commit}){
let response = await Api().get('/event-names')
let eventNames = response.data.data
eventNames.forEach(e => {
e.attributes.id = e.id
})
commit('SET_EVENTNAMES', eventNames.map(e => e.attributes))
}
}
}
App.vue
<script>
import { mapState } from 'vuex';
export default {
name: 'App',
created(){
this.$store.dispatch('events/loadAll');
this.$store.dispatch('users/loadCurrent');
},
computed: {
...mapState({
currentUser: state => state.users.currentUser,
snackbars: state => state.snackbar.snackbars
})
},
data: () => ({
drawer: null,
items: [
{ title: 'Schedule', icon: 'mdi-calendar-month', to: '/' },
{ title: 'Results', icon: 'mdi-calendar-check', to: '/Results' },
{ title: 'Points', icon: 'mdi-format-list-numbered', to: '/Points' },
{ title: 'About', icon: 'mdi-help-box', to: '/About' },
],
}),
methods: {
logoutUser() {
this.$store.dispatch("users/logout");
}
},
}
</script>
I can see the following row in the index.js:
import eventsModule from './events';
But you listed the event.js file. Is this a typo? Have you listed the content of the events.js?
If you want to call the action as this.$store.dispatch('events/loadAll') you have to change the module name:
...
export default new Vuex.Store({
modules: {
snackbar: snackbarModule,
events: eventsModule, // <- change the key name to 'events'
users: usersModule
}
})
I think this question is already answered, although there are some note that i want to point out.
To improve your code readability, you should use the right helper. So a good practice to follow is the use of mapGetters and mapActions instead of using mapState.
So refactoring your code it would be like with Max corrections:
// index.js
import Vue from 'vue'
import Vuex from 'vuex'
import snackbarModule from './snackbar';
import eventsModule from './events';
import usersModule from './users';
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
snackbar: snackbarModule,
events: eventsModule, // <-module name correction
users: usersModule
}
})
// events.js <- filename correction
import Api from "../service/api"
export default {
namespaced: true,
state: {
eventNames: [],
},
getters: {
GET_EVENTNAMES: (state) => state.eventNames // use getters instead of using state to prevent mutations in the state
},
mutations: {
SET_EVENTNAMES(state, eventNames) {
state.eventNames = eventNames
}
},
actions: {
async loadAll({commit}){
let response = await Api().get('/event-names')
let eventNames = response.data.data
eventNames.forEach(e => {
e.attributes.id = e.id
})
commit('SET_EVENTNAMES', eventNames.map(e => e.attributes))
}
}
}
// App.vue
<script>
import { mapGetters, mapActions } from 'vuex';
export default {
name: 'App',
created(){
this.loadAll(); // called from methods/mapActions
this.loadCurrent(); // called from methods/mapActions
},
computed: {
...mapGetters({
currentUser: 'users/currentUser',
snackbars: 'snackbar/snackbars'
})
...mapGetters('events', [ // Can be used as an Array or as an Object
'GET_EVENTNAMES'
])
},
data: () => ({
drawer: null,
items: [
{ title: 'Schedule', icon: 'mdi-calendar-month', to: '/' },
{ title: 'Results', icon: 'mdi-calendar-check', to: '/Results' },
{ title: 'Points', icon: 'mdi-format-list-numbered', to: '/Points' },
{ title: 'About', icon: 'mdi-help-box', to: '/About' },
],
}),
methods: {
...mapActions('users', [ // Can be splited by modules or all together removing the module parameter ('users')
'logout',
'loadCurrent'
]),
...mapActions('events', [
'loadAll'
]),
logoutUser() {
this.logout(); // Can be used as an Array or as an Object
}
},
}
</script>

Vuex state changes are not propagated to Vue component template

I just started working on Vue and Vuex. I have created a component with its state data in Vuex. After an action, I can see my state changes applied in mutation, however, my Vue component is still not able to pick the new changes up.
Here's my store file:
const state = {
roomInfo: {
gameID: null,
userID: null,
},
seats: null,
};
const getters = {
seats: state => state.seats,
roomInfo: state => state.roomInfo,
};
const actions = {
async streamSeats({ commit }) {
let connection = new WebSocket(`ws://localhost:8080/api/game/${state.roomInfo.gameID}/seats/${state.roomInfo.userID}`)
connection.onmessage = function(event) {
commit('setSeats', event.data);
}
connection.onopen = function() {
console.log("Successfully connected to the echo websocket server...")
}
connection.onerror = function(event) {
console.log("ERRR", event)
}
},
async setRoomInfo({ commit }, roomInfo) {
commit('setRoomInfo', roomInfo);
},
};
const mutations = {
setSeats: (state, seats) => {
state.seats = seats
// I can see changes here properly
console.log(seats);
},
setRoomInfo: (state, roomInfo) => {
state.roomInfo.gameID = roomInfo.gameID;
state.roomInfo.userID = roomInfo.userID;
if (roomInfo.seatNumber === 1) {
state.seats.p1.id = roomInfo.userID;
}
},
};
export default {
state,
getters,
actions,
mutations,
};
And this is my component:
<template>
{{ seats }}
</template>
<script>
/* import API from '../api' */
import { mapGetters, mapActions } from 'vuex';
export default {
name: "Seats",
methods: {
...mapActions([
'streamSeats',
'setRoomInfo',
]),
},
computed: {
...mapGetters([
'seats',
'roomInfo',
'setSeats',
]),
},
watch: {
roomInfo: {
handler(newValue) {
if (newValue.userID && newValue.gameID) {
this.streamSeats();
}
},
deep: true,
},
},
components: {},
data: function() {
return {
alignment: 'center',
justify: 'center',
}
},
created() {
let gameID = this.$route.params.id
this.setRoomInfo({
gameID: gameID,
userID: this.$route.params.userID,
seatNumber: 1,
});
},
}
</script>
As you can see, I'd like to change the state data for seats inside state, after it connects to websocket server.
I have spent a long time trying to figure this out with no luck. I've tried to use mapstate, data, and a few other tricks without any luck. I tried all the suggested solutions in similar stackoverflow threads as well. I'd really appreciate if someone could give me some hints on how to pass this obstacle.
There are some mismatch when you define getters and call mapGetters
store
const getters = {
seatsd: state => state.seats, // there is a typo in seats, you declared seatsd
roomInfo: state => state.roomInfo,
};
component
computed: {
...mapGetters([
'seats',
'roomInfo',
'setSeats', // this is not getters, this is mutations
]),
},
Thank you for looking at it. I installed Vuejs chrome extension today. Apparently it changed the way errors were displayed in chrome dev console. I just noticed I had a few uncaught errors elsewhere, which didn't allow the code to go through these parts properly. After resolving those issues, I was able to see the data in my component.

Vuejs with namespaced modules and unknow mutation type

i have created two store modules and I did the import into main store.
When I load my drawer view, I am getting the next error.
What am I doing wrong here
error:vuex.esm.js [vuex] unknown mutation type: SET_DRAWER
//Drawer.vue
.........
computed: {
...mapState("navstore", ["barColor", "barImage"]),
drawer: {
get() {
return this.$store.state.navstore.drawer;
},
set(val) {
this.$store.commit("SET_DRAWER", val);
},
},
computedItems() {
return null;
//this.items.map(this.mapItem);
},
profile() {
return {
avatar: true,
title: "Gestan",
};
},
},
methods: {},
.........
.........
//store/index.js
import Vue from "vue";
import Vuex from "vuex";
import { default as auth } from ".auth";
import { default as navstore } from "./navStore";
Vue.use(Vuex);
export default new Vuex.Store({
modules: { auth: auth, navstore: navstore },
});
//navstore.js
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const SET_BAR_IMAGE = "NAVSTORE/SET_BAR_IMAGE";
const SET_DRAWER = "NAVSTORE/SET_DRAWER";
export default {
namespaced: true,
state: {
barColor: "rgba(0, 0, 0, .8), rgba(0, 0, 0, .8)",
barImage:
"https://demos.creative-tim.com/material-dashboard/assets/img/sidebar-1.jpg",
drawer: null,
},
mutations: {
[SET_BAR_IMAGE](state, payload) {
state.barImage = payload;
},
[SET_DRAWER](state, payload) {
state.drawer = payload;
},
},
actions: {
actionSetDrawer({ commit }, payload) {
commit(SET_DRAWER, payload);
},
},
};
//auth.js
import Vue from "vue";
import Vuex from "vuex";
import * as storage from "#/store/storage";
import services from "#/services/api/AuthenticationService";
Vue.use(Vuex);
const SET_USER = "AUTH/SET_USER";
const SET_TOKEN = "AUTH/SET_TOKEN";
export default {
namespaced: true,
state: {
token: null,
user: null,
isUserLoggedIn: false,
},
mutations: {
[SET_TOKEN](state, token) {
state.token = token;
state.isUserLoggedIn = !!token;
},
[SET_USER](state, user) {
state.user = user;
},
},
getters: {
isAuthenticated: (state) => !!state.token,
// authStatus: state => state.status
},
actions: {
actionDoLogin({ dispatch }, payload) {
return services.login(payload).then((res) => {
dispatch("actionSetUser", res.data.user);
dispatch("actionSetToken", res.data.token);
});
},
};
You need to remove prefixes with slash from mutation names because your modules namespaced and you will always access this mutations outside indicating a module name like this moduleName/mutation.
For instance:
const SET_BAR_IMAGE = "NAVSTORE/SET_BAR_IMAGE";
const SET_DRAWER = "NAVSTORE/SET_DRAWER";
// should be
const SET_BAR_IMAGE = "SET_BAR_IMAGE";
const SET_DRAWER = "SET_DRAWER";
Because the SET_DRAWER mutation is inside a navspaces module you should call it indicating a module name:
this.$store.commit("navstore/SET_DRAWER", val);
Don't try to call actions inside actions like this:
actionDoLogin({ dispatch }, payload) {
return services.login(payload).then((res) => {
dispatch("actionSetUser", res.data.user);
dispatch("actionSetToken", res.data.token);
});
},
Use mutations in a desired combination:
actionDoLogin({ dispatch }, payload) {
return services.login(payload).then((res) => {
commit(SET_USER, res.data.user);
commit(SET_TOKEN, res.data.token);
});
},