Hey,
I am also having problems getting to the store from my routes. I want to use a guard only on specific parent routes and this guard needs access to the store. My router/index can have {store} in the export function part, but I need it within my guard, which is imported within my routes.js, which in turn is imported from router/index. So I don’t know how it would help me that I can inject the { store } in my router/index as I need it in other modules.
Since the store exports a function, I just called this function to receive it, but I am getting a lot of "don’t mutate the store directly’ messages, although none of my actions does anything to the state directly.
This is my guard:
import {actions} from '@store/auth/actions';
import getStore from '@store';
export const loggedInGuard = async (to, from, next) => {
let store = getStore();
if (store.getters.isLoggedIn) {
return next();
}
try {
await store.dispatch(actions.LOGIN);
} catch(e) {
}
if (store.getters.isLoggedIn) {
next();
} else {
next({name: 'login', query: {redirect: to.fullPath}});
}
}
And this is my login action:
async [actions.LOGIN]({ dispatch, commit, state}) {
let response = {};
try {
response = await axios({
url: `${constants.API_URL}/user`,
method: 'get',
});
if (response.payload && response.payload.data) {
commit(mutations.SET_LOGGED_IN_USER, response.payload.data);
return Promise.resolve(true);
}
} catch (e) {
}
return Promise.reject('User data could not be retrieved');
}
The commit(mutations.SET_LOGGED_IN_USER, response.payload.data);
does have 2 lines only, where I am just doing something like this.state.user = user
and another similar line, and they both throw 2 errors, reading:
Error in callback for watcher "function () { return this._data.$$state }": "Error: [vuex] do not mutate vuex store state outside mutation handlers."
vue.runtime.esm.js?2b0e:1888 Error: [vuex] do not mutate vuex store state outside mutation handlers.
at assert (vuex.esm.js?2f62:90)
at Vue.store._vm.$watch.deep (vuex.esm.js?2f62:774)
at Watcher.run (vue.runtime.esm.js?2b0e:4562)
at Watcher.update (vue.runtime.esm.js?2b0e:4536)
at Dep.notify (vue.runtime.esm.js?2b0e:730)
at Object.reactiveSetter [as user] (vue.runtime.esm.js?2b0e:1055)
at Store.eval (mutations.js?a46e:17)
at wrappedMutationHandler (vuex.esm.js?2f62:725)
at commitIterator (vuex.esm.js?2f62:391)
at Array.forEach (<anonymous>)
I would really appreciate some help
I am trying to figure this out for hours now and I just don’t get why these errors come up… 