So, in my project (Vue-cli + TypeScript) I need to store user data to locaStorage. For this purpose I decide to use vuex-persist (npm plugin) alongside with vuex. But in DevTool, in localStorage doesn't appear anything. What is wrong in my code. Thank you in advance.
In precedent project I already used this combination of tools, and they work fine. In this project I use the same configuration, and it doesn't work . And this is the most strange thing.
This is StructureModule.ts
import { ActionTree, MutationTree, GetterTree, Module } from "vuex";
const namespaced: boolean = true;
interface IDataStructure {
name: string;
type: string;
description: string;
}
interface IStructureState {
name: string;
description: string;
props: IDataStructure[];
}
export interface IState {
structures: IStructureState[];
}
export const state: IState = {
structures: [
{
name: "",
description: "",
props: [
{
name: "",
type: "",
description: "",
},
],
},
],
};
export const actions: ActionTree<IState, any> = {
addNewDataStructure({ commit }, payload: IStructureState): void {
commit("ADD_DATA_STRUCTURE", payload);
},
updateDataStructure({ commit }, payload: IStructureState): void {
commit("UPDATE_EXISTING_DATA_STRUCTURE", payload);
},
clearDataStructure({ commit }, { name }: IStructureState): void {
commit(" CLEAR_DATA_STRUCTURE", name);
},
};
export const mutations: MutationTree<IState> = {
ADD_DATA_STRUCTURE(state: IState, payload: IStructureState) {
if (state.structures[0].name === "") {
state.structures.splice(0, 1);
}
state.structures.push(payload);
},
CLEAR_DATA_STRUCTURE(state: IState, name: string) {
state.structures.filter((structure: IStructureState) => {
if (structure.name === name) {
state.structures.splice( state.structures.indexOf(structure), 1);
}
});
},
UPDATE_EXISTING_DATA_STRUCTURE(state: IState, payload: IStructureState) {
state.structures.map((structure: IStructureState) => {
if (structure.name === payload.name) {
state.structures[state.structures.indexOf(structure)] = payload;
}
});
},
};
export const getters: GetterTree<IState, any> = {
dataStructureByName(state: IState, structName: string): IStructureState[] {
const structure: IStructureState[] = state.structures.filter((struct: IStructureState) => {
if (struct.name === structName) {
return struct;
}
});
return structure;
},
dataStructures(): IStructureState[] {
return state.structures;
},
};
export const StructureModule: Module<IState, any> = {
namespaced,
state,
mutations,
actions,
getters,
};
This is index.ts
import Vue from "vue";
import Vuex, { ModuleTree } from "vuex";
import VuexPersistence from "vuex-persist";
import { StructureModule , IState} from "./modules/StructureModule";
Vue.use(Vuex);
const storeModules: ModuleTree<IState> = {
StructureModule,
};
const vuexPersistentSessionStorage = new VuexPersistence({
key: "test",
modules: ["StructureModule"],
});
export default new Vuex.Store<any>({
modules: storeModules,
plugins: [vuexPersistentSessionStorage.plugin],
});
This is main.ts
import store from "#/store/index.ts";
import * as $ from "jquery";
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
global.EventBus = new Vue();
(global as any).$ = $;
Vue.config.productionTip = false;
console.log(store);
new Vue({
router,
store,
render: (h) => h(App),
}).$mount("#app");
This is vue.config.js
module.exports = {
transpileDependencies: ["vuex-persist"],
};
This is store in vue-devtool
And this is dev-tool localStorage
I expect that in localstorage to appear an storage with key "test" with predefined values, but instead of this localStorage is empty.
As said in the guide
The only way to actually change state in a Vuex store is by committing
a mutation
https://vuex.vuejs.org/guide/mutations.html
I don't see any mutation in your code.
Otherwise, you should take a look at https://github.com/robinvdvleuten/vuex-persistedstate, it seems to be more popular, and I've been using it without any problem.
Usage is very simple : you just need to declare a plugin inside your store:
import createPersistedState from 'vuex-persistedstate'
const store = new Vuex.Store({
// ...
plugins: [createPersistedState()],
})
I found solution for this problem.
In my case i just remove namespaced from
export const StructureModule: Module<IState, any> = {
namespaced, <----- This
state,
mutations,
actions,
getters,
};
It seems namespaced should be used only if you have more than one module.
Related
In my component there are conditionals and labels using route.meta.
import { useRoute } from 'vue-router';
const route = useRoute();
const name = route.meta?.name;
When running the test in Cypress I get an error
TypeError: Cannot read properties of undefined (reading 'meta')
I have attempted to use mocking the route however this doesn't resolve the issue
const mountTalentCommunityDetailsPage = (props: Record<string, unknown>) => {
const mockRoute = {
params: {
meta: {},
},
}
return mount(
{
components: {
MyComponent,
},
template: `<MyComponent/>`,
},
{
global: {
mocks: {
$route: mockRoute,
},
provide: {
useRoute,
},
},
}
)
}
Alternatively I could update name to const name = route.meta?.name; , however I don't think it's great to update this to fit the test
Thank you in advance!
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))
I try to implement vuex modules and understand usage. While trying to import modules in my home.vue, I have found this solution:
import { FETCH_INDEX_ARTICLES } from "#/store/types/actions.type.js";
// imports this => export const FETCH_INDEX_ARTICLES = "fetchIndexArticles"
import { mapGetters, mapActions} from 'vuex'
export default {
name: "Home",
data() {
return {}
},
computed: {
...mapGetters(['articles']),
},
methods: {
...mapActions([FETCH_INDEX_ARTICLES])
}
created() {
this.$store.dispatch(FETCH_INDEX_ARTICLES);
}
};
but instead I get
vuex.esm.js?2f62:438 [vuex] unknown action type: fetchIndexArticles
vuex.esm.js?2f62:950 [vuex] unknown getter: articles
store/index.js
export default new Vuex.Store({
modules: {
articles,
}
});
store/modules/articles.js
const state = {
articles: [],
};
const getters = {
articles(state) {
return state.articles;
},
};
const mutations = {
[SET_ARTICLES] (state, pArticles) {
state.article = pArticles
state.errors = {}
}
}
const actions = {
[FETCH_INDEX_ARTICLES] (context) {
context.commit(FETCH_START)
return ApiService
.get('/articlelist/index/')
.then((data) => {
context.commit(SET_ARTICLES, data.articles);
context.commit(FETCH_END)
})
.catch((response) => {
context.commit(SET_ERROR, response.data.errors);
})
}
};
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
How can I correctly import vuex module?
Thanks
You must specify your modules,
Your way is valid when you import your modules directly into your component
...mapGetters('articles', {
article: 'articles',
})
this.article(2)
https://vuex.vuejs.org/guide/modules.html#binding-helpers-with-namespace
To facilitate the use I use the method dispatch for actions
this.$store.dispatch('articles/FETCH_INDEX_ARTICLES', {anydata})
I am trying to get into the way of things with Vue but I've got some troubles with:
1: I cannot get access to my getters from router/index.js file. (I can get access to it but it return like a function with returns function with I cannot call and get the value)
2: I cannot set up guard properly. With Angular it's much easier
What am I doing wrong here? Any suggestions?
Router code
/* eslint-disable no-undef */
import Vue from "vue";
import VueRouter from "vue-router";
// import auth from '../store/modules/auth';
import { createNamespacedHelpers } from "vuex";
const { mapGetters } = createNamespacedHelpers("auth");
// import store from '../store';
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "Home",
component: () => import("../components/Home.vue"),
meta: { requiresAuth: true }
},
{
path: "/users",
name: "Users",
component: () => import("../components/Users/Users.vue"),
meta: { requiresAuth: true }
},
{
path: "/sign-in",
name: "SignIn",
component: () => import("../components/SignIn/SignIn.vue"),
}
];
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes
});
router.beforeEach((to, from, next) => {
const storeGetters = { ...mapGetters(['isAuthenticated', 'authStatus', 'test']) };
const isUserLoggedIn = storeGetters.isAuthenticated;
if (to.matched.some(record => record.meta.requiresAuth)) {
if (isUserLoggedIn) {
console.log('user is authenticated');
to; from;
return next();
} else {
console.log('Access denied!');
next({
path: '/signIn',
query: { redirect: to.fullPath }
});
}
next({
path: '/signIn',
query: { redirect: to.fullPath }
});
} else {
next();
}
})
export default router;
Vuex index
import Vue from "vue";
import Vuex from "vuex";
import modules from "./modules"
Vue.use(Vuex);
export default new Vuex.Store({
strict: true,
modules,
state: {
testState: 'State value'
},
getters: {
test: state => state
}
});
auth module (vuex)
import { apolloClient } from '#/vue-apollo';
import SignInGQL from "#/graphql/signIn.gql";
export default {
namespaced: true,
state: {
token: null,
authStatus: false
},
getters: {
isAuthenticated: (state) => {
console.log('state: ', state);
return !!state.token;
},
authStatus: state => state.authStatus,
test: state => state.authStatus
},
actions: {
async signIn({ commit, dispatch }, formInput) {
try {
const { data } = await apolloClient.mutate({
mutation: SignInGQL,
variables: { ...formInput }
})
const { token } = data.signIn;
await commit('setToken', token);
localStorage.setItem('auth-token', token);
await dispatch('setUser', token);
} catch (e) {
console.error(e)
}
},
async setUser({ commit }, token) {
const encodedPayload = token.split('.')[1];
const { payload } = JSON.parse(atob(encodedPayload));
// TODO: Set User information
await commit('signInUser', payload);
}
},
mutations: {
setToken(state, token) {
state.token = token
},
signInUser(state, user) {
console.log('authStatus: ', state.authStatus)
state.authStatus = true
state.user = { ...user }
console.log('authStatus: ', state.authStatus)
},
logOutUser(state) {
console.log('dispatched logOutUser')
state.authStatus = ''
state.token = '' && localStorage.removeItem('auth-token')
}
}
}
It seems createNamespacedHelpers is just complicating things. Import the store:
import store from '#/store'; // <-- aliased path
Use the getters like this:
const isAuthenticated = store.getters['auth/isAuthenticated'];
const authStatus = store.getters['auth/authStatus'];
const test = store.getters['auth/test'];
The first portion of the string is the Vuex module name, followed by the getter name.
Not only is this simpler to use, it's more readable and clear which module the getter comes from when studying the code.
I faced the same problem...
Every time I tried to retrieve the getter's data inside the router it returned the function itself instead of the desired function's return value.
The solution:
In my code I used to call the createStore method inside the main.js file, but in order to be able to call the store's getters inside the vue-router you need to refactor your code, calling createStore in the same index.js file you declared it:
Before refactoring:
main.js file...
import store from './modules/index.js'
import { createStore } from 'vuex';
const mainStore = createStore(store)
app.use(store)
index.js file (Vuex store)...
const store = { ... store code here ... }
export default store
After refactoring:
main.js file...
import store from './modules/index.js'
app.use(store)
index.js file (Vuex store)...
import { createStore } from 'vuex';
const store = createStore({ ... store code here ... })
export default store
Humbly, I admit that I'm gleaning from SAVuegram in setting up authentication for my app. I am running Firebase's onAuthStateChanged to make certain the user stays logged in during page refreshes however I am completely unable to access the state inside of the function, receiving the following error.
(the $store is just from me taking a screenshot while testing "$store" as well as "store" - both break.)
With strict debugging turned on I'm also getting messages warning me about mutating outside of mutation handlers, but isn't that what I'm doing?
Here's my store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import fb from '../components/firebase/firebaseInit'
import createLogger from 'vuex/dist/logger'
// import dataRefs from './dataRefs'
// import pageTitle from './modules/pageTitle'
import auth from './modules/auth'
import apps from './modules/applicants'
Vue.use(Vuex)
fb.auth.onAuthStateChanged(user => {
if (user) {
// here I can access the user object but never the following "store"
console.log("FB AUTH", user);
store.commit('setCurrentUser', user)
store.dispatch('fetchUserProfile')
}
});
const debug = process.env.NODE_ENV !== 'production'
const createStore = () => {
return new Vuex.Store({
state: {
pageTitle: '',
currentUser: null,
userProfile: null
},
mutations: {
changePageTitle(state, newTitle) {
state.pageTitle = newTitle
},
changeSnackBarMessage(state, newMessage) {
state.snackBarMessage = newMessage
},
// POPUPS
changeAdvisorAddAppPopupStatus(state) {
state.showAdvisorAddPopup = !state.showAdvisorAddPopup
},
setToken(state, token) {
state.token = token;
},
setUser(state, userObj) {
state.user.email = userObj.email;
state.user.fbUUID = userObj.uuid;
}
},
actions: {
updatePageTitle(vuexContext, newTitle) {
vuexContext.commit('changePageTitle', newTitle);
},
updateSnackBarMessage(vuexContext, newMessage) {
vuexContext.commit('changeSnackBarMessage', newMessage);
},
toggleAdvisorAddPopup(vuexContext) {
vuexContext.changeAdvisorAddAppPopupStatus
},
},
modules: {
auth,
apps
},
strict: debug,
plugins: debug ? [createLogger()] : []
})
};
export default createStore;
FYI, I have also tried to instantiate my store by using export const store = new Vuex.Store({ instead of the const create ... method but then Vuex show me that none of my state, actions, getters, or mutations are even found.
Thanks for the help.
Why do you create the store in a function?
const createStore = () => {
I am just doing it like that:
const store = new Vuex.Store({
state: {},
mutations: {},
actions: {},
modules: {
auth,
apps
},
strict: debug,
plugins: debug ? [createLogger()] : []
})
};
export default store;
And i am able to access store now.