Call store mutation from vs file
-
Hello all, assuming i didn’t deviate from the quasar default architecture at all, how do i call a mutation from inside a js file?
I would think simply import the store
import store from '../store' store.dispatch('auth/setLoggedIn', false)
but i’m getting
_store_index__WEBPACK_IMPORTED_MODULE_2__.default.dispatch is not a function
-
What is in your
index.js
under the/store
folder? i.e. are you following the module system Quasar suggests?Scott
-
I didn’t change it from what is there cept i’m importing different modules
for example:import auth from './modules/store-auth';
and adding them to the Vuex.Store instance. Otherwise no change.
So it does work perfectly in .vue files. Just can’t seem to figure it out in .js files
-
Ok. Try something like this.
store('store-auth').dispatch('auth/setLoggedIn', false)
Scott
-
Thanks Scott but sadly didn’t work. getting a long list of error about not mutating state outside of mutations though the action i called just did a console.log
-
any other ideas?
-
Hard to say without looking at all your code. Maybe create a sandbox and we can look at it? https://codesandbox.quasar.dev
Scott
-
figured it out and in hindsight very simple. I copied this from a tutorial on Quasar but i’m intercepting each router request in a boot file and allowing or disallowing based on whether or not user is authenticated… though i’m using JWT from a Spring Boot backend. Anyway, I also wanted to set ‘loggedIn’ in the auth store since other components need to know if the user is logged in.
boot/router-auth.js
import { LocalStorage } from "quasar"; import { AUTH } from "../constants"; export default ({ router, store }) => { router.beforeEach((to, from, next) => { let loggedIn = !tokenExpired(); store.commit("auth/setLoggedIn", loggedIn); if (checkAccess(loggedIn, to)) { next("/auth/login"); } else { next(); } }); }; const tokenExpired = () => { const token = localStorage.getItem(AUTH.TOKEN); const expiration = LocalStorage.getItem(AUTH.TOKEN_EXPIRE); return new Date() >= expiration || token == null; }; const checkAccess = (loggedIn, to) => { return ( !loggedIn && ![ "", "/", "/auth/login", "/auth/register", "/password/reset", "/password/reset/new" ].includes(to.path) ); };
So works great but what do you think of this strategy? Better way to do it?