beforeRouteEnter function and Vuex problem - vue.js

In the quasar project, I have a Vuex function "asyncValidateToken" that checks whether the user is logged in to the system. It is located in the file "src/store/index.js". The file contains the following code:
import Vue from 'vue'
import Vuex from 'vuex'
import { api } from 'boot/axios'
Vue.use(Vuex)
export default function (/* { ssrContext } */) {
const Store = new Vuex.Store({
state: {
isLogin: false
},
mutations: {
changeIsLogin (state, payload) {
state.isLogin = payload;
}
},
actions: {
asyncValidateToken: async (context, payload) => {
await api.post('/accounts/token', '', {
headers: {
'Authorization': `Bearer ${localStorage.token}`,
}
})
.then(response => {
if (response.data == localStorage.userId) {
context.commit('changeIsLogin', true);
return true;
} else {
context.commit('changeIsLogin', false);
return false;
}
})
.catch(error => {
context.commit('changeIsLogin', false);
return false;
});
}
}
})
return Store
}
The page "Results.vue" where the route protection is used via the function "beforeRouteEnter"
<template>
<q-page class="flex flex-center">
<div>
<charts />
<feedback />
</div>
</q-page>
</template>
<script>
import Charts from 'src/components/Charts.vue'
import Feedback from 'src/components/Feedback.vue'
import store from 'src/store/index.js'
export default {
name: 'Results',
components: {
Charts,
Feedback
},
beforeRouteEnter (to, fromR, next) {
if (store.dispatch('asyncValidateToken')) {
next();
} else { this.$router.push('/login'); }
}
}
</script>
I get an error "src_store_index_js__WEBPACK_IMPORTED_MODULE_2__.default.dispatch is not a function
at beforeRouteEnter (Results.vue?82a0:23)
at routeEnterGuard (vue-router.esm.js?85f8:2333)". The construction "this.$store.dispatch('asyncValidateToken')" also does not work. Why?

Try
store().dispatch('')
Why?
Because your store.js module is exporting a function as default, and it returns the store.

Related

vuex error with quasar $store.auth is undefined

I am trying to use vuex with Quasar. I have created an authentication module as below.
// src/store/auth/index.js
import { api } from 'boot/axios';
export default {
state: {
user: null,
},
getters: {
isAuthenticated: state => !!state.user,
StateUser: state => state.user,
},
mutations: {
setUser(state, username){
state.user = username
},
LogOut(state){
state.user = null
},
},
actions: {
LOGIN: ({ commit }, payload) => {
return new Promise((resolve, reject) => {
api
.post(`/api/login`, payload)
.then(({ data, status }) => {
if (status === 200) {
commit('setUser', data.refresh_token)
resolve(true);
}
})
.catch(error => {
reject(error);
});
});
},
}
}
I imported it in the store
// src/store/index.js
import { store } from 'quasar/wrappers'
import { createStore } from 'vuex'
import auth from './auth'
export default store(function (/* { ssrContext } */) {
const Store = createStore({
modules: {
auth:auth
},
// enable strict mode (adds overhead!)
// for dev mode and --debug builds only
strict: process.env.DEBUGGING
})
return Store
})
And I imported it into MainLayout to check if the user is logged in.
// src/layouts/MainLayout
<template>
</template>
<script>
import { ref, onMounted } from 'vue'
import packageInfo from '../../package.json'
import { useStore } from 'vuex'
export default {
name: 'MainLayout',
setup () {
const $store = useStore;
const connected = ref(false);
function checkLogin(){
//console.log($store)
return connected.value = $store.auth.isAuthenticated
};
onMounted(()=> {
checkLogin();
});
return {
appName: packageInfo.productName,
link:ref('dashboard'),
drawer: ref(false),
miniState: ref(true),
checkLogin,
}
}
}
</script>
But every time, I get the same error :
$store.auth is undefined
I tried to follow the quasar documentation, but I can't. Can anyone tell me what I am doing wrong please?
Thank you.
Someone helped me to find the solution. My error is to have written const $store = useStore instead of const $store = useStore(). Thanks

Vuex action not works with namespaced inside Nuxt fetch

I am building my own small project. When i try to access states from main store (index.js) inside of nuxt fetch method all works fine, but while i am trying to access from namespaced(store/photos.js) store it wont work. Here is my code.
store/index.js ( Works )
export const state = () => ({
fetchedData: []
})
export const mutations = {
setData: (state, data) => {
state.fetchedData = data;
}
}
export const actions = {
async get(vuexContext) {
const requestedData = await this.$axios.get("https://jsonplaceholder.typicode.com/users");
vuexContext.commit('setData', requestedData.data);
},
}
my Component:
<script>
import { mapState, mapActions } from 'vuex'
export default {
async fetch({ error,store })
{
try {
await store.dispatch('get');
} catch (error) {
console.log(error);
}
},
computed: {
...mapState(['fetchedData'])
}
};
</script>
store/photos.js ( Does not works )
export const state = () => ({
list: []
});
export const mutations = {
setPhotos(state, data) {
state.list = data;
}
};
export const actions = {
async getPhotos(vuexContext, context) {
const requestedData = await this.$axios.get(
"https://jsonplaceholder.typicode.com/photos"
);
vuexContext.commit("setPhotos", requestedData.data);
}
};
Same Component but modified
<script>
import { mapState, mapActions } from 'vuex'
export default {
async fetch({ error,store })
{
try {
await store.dispatch('photos/getPhotos');
} catch (error) {
console.log(error);
}
},
computed: {
...mapState({
list : 'photos/list'
})
}
};
</script>
Thanks in advance.
namespaced: true,
You can add this to your index.js file. Hope this will work.
Reference link:
Try this

Why is Vuex not detected after refresh page? (nuxt)

Vuex is not detected after refresh, but all data is output to the console. Also after refresh, some components behave incorrectly. For example, I use vee-validate and all the rules and fields I get from the back, after refresh the validation rules disappear, but the fields are displayed
Vuex works on all pages but after refresh only on the home page
stroe/index.js
export const state = () => ({});
const map = {
ru: "ru",
uk: "uk-ua"
};
export const getters = {
lang(state) {
return map[state.i18n.locale];
}
};
export const mutations = {};
export const actions = {
async nuxtServerInit({ state, dispatch }) {
try {
await dispatch('category/getCategories', {
});
} catch (err) {
console.log('nuxt server init error', err);
}
}
};
home page (everything works)
<template>
<div>
<main class="home-page">
<banner />
<section class="home_page">
<div class="container">
<phone-pay />
<card-pay />
<categories :categories="categories" :services="services" />
<main-banner />
</div>
</section>
</main>
</div>
</template>
<script>
import Banner from "#/components/Index/Banner";
import PhonePay from "#/components/Index/PhonePay";
import CardPay from "#/components/Index/CardPay";
import Categories from "#/components/Index/Categories";
import MainBanner from "#/components/Index/MainBanner";
export default {
components: {
Banner,
PhonePay,
CardPay,
Categories,
MainBanner
},
async asyncData({ store, app: { $api }, error, req }) {
try {
const {
data: { data: categories, included: services }
} = await $api.CategoryProvider.getPopularCategories({
params: {
include: "services"
}
});
return {
lang: store.getters.lang,
categories,
services
};
} catch (e) {
console.log("error index", e);
error({ statusCode: 404, message: "Page not found" });
}
}
};
</script>
category (does not work)
<template>
<services-viewer :initial-services="initialServices" :category="category" :init-meta="initMeta" />
</template>
<script>
import ServicesViewer from "#/components/UI/ServicesViewer";
export default {
components: {
ServicesViewer
},
async asyncData({ store, route, error, app: { $api } }) {
try {
const {
data: { data: initialServices, meta: initMeta }
} = await $api.ServiceProvider.getServices({
params: {
"filter[category_slug]": route.params.id,
include: "category"
// "page[size]": serviceConfig.SERVICE_PAGINATION_PAGE_SIZE
}
});
await store.dispatch("category/getCategories", {
params: {}
});
const category = store.state.category.categories.find(
({ attributes: { slug } }) => slug === route.params.id
);
return {
initialServices,
category,
initMeta
};
} catch (e) {
const statusCode = e && e.statusCode ? e.statusCode : 404;
error({ statusCode });
}
}
};
</script>
install the below package:
npm install --save vuex-persistedstate
then change your store like below, then your data will be available after refresh the page.
// store/index.js
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate'
const createStore = () =>
new Vuex.Store({
plugins: [createPersistedState()],
state: {
},
mutations: {
},
getters:{
}
});
export default createStore;
for more details you can read from here.
I solved it. It was my mistake. I have a parallax plugin that works on the home page, but if you go to another page and refresh, the plugin starts and cannot find the item and breaks the page.
follow this link for your question
The nuxtServerInit Action
If the action nuxtServerInit is defined in the store and the mode is universal, Nuxt.js will call it with the context (only from the server-side). It's useful when we have some data on the server we want to give directly to the client-side.
For example, let's say we have sessions on the server-side and we can access the connected user through req.session.user. To give the authenticated user to our store, we update our store/index.js to the following:
actions: {
nuxtServerInit ({ commit }, { req }) {
if (req.session.user) {
commit('user', req.session.user)
}
}
}

Vuex getter always return null

When i use vuex getter in my vue.js component it return null for me.
Here is my code
MainLayout.vue
<script>
import NavBar from '#/components/NavBar.vue'
import ToolBar from "#/components/ToolBar"
import { mapActions, mapGetters } from 'vuex'
export default {
name: "MainLayout",
components : {
ToolBar, NavBar
},
data: () => ({
drawer: null,
}),
computed: {
...mapGetters([
'error',
]),
},
methods: {
close() {
this.$store.commit('SET_ERROR', null)
},
}
}
</script>
<template>
<div id="main">
<v-navigation-drawer clipped v-model="drawer" app>
<nav-bar></nav-bar>
</v-navigation-drawer>
<tool-bar #toggleDrawer="drawer = !drawer"/>
<v-content>
<v-container class="fill-height" fluid>
<router-view></router-view>
</v-container>
</v-content>
<v-snackbar :timeout="0" :value="error">
{{ error }}
<v-btn color="red" text #click="close">
Close
</v-btn>
</v-snackbar>
</div>
</template>
<style scoped>
</style>
Here is NavBar.vue
<script>
import { mapGetters } from 'vuex'
export default {
data: () => ({
}),
computed: {
...mapGetters([
'authUser'
]),
isAdmin() {
return this.authUser.role.name == 'admin'
},
}
}
</script>
Vuex module auth.js
import api from '#/api'
import {clearAccessToken, setAccessToken} from '#/auth'
import router from '#/router'
const state = {
loading: null,
user: null
}
const mutations = {
SET_LOADING: (state, loading) => {
state.loading = loading
},
SET_USER: (state, user) => {
state.user = user
}
}
const getters = {
loading: state => {
return state.loading
},
loggedIn: (state) => {
return !!state.user
},
authUser: (state) => {
return state.user
},
}
const actions = {
async login({commit, dispatch }, user) {
commit('SET_LOADING', true)
try {
const data = await api.post('/api/auth/login', { user })
setAccessToken(data.token)
await dispatch('getUser')
commit('SET_LOADING', false)
router.push('/')
} catch (e) {
commit('SET_LOADING', false)
dispatch('handleError', e)
}
},
async getUser({commit, dispatch}) {
try {
const user = await api.get('/api/auth/user')
commit('SET_USER', user.data)
return user
} catch (e) {
clearAccessToken()
dispatch('handleError', e)
}
},
async logout({commit, dispatch}) {
try {
await api.post('/api/auth/logout')
clearAccessToken()
router.push('/login')
} catch(e) {
dispatch('handleError', e)
}
}
}
export default {
namespaced: false,
state,
getters,
actions,
mutations,
}
When i run this code i have next error
[Vue warn]: Error in render: "TypeError: Cannot read property 'role' of null"
But if i add code
isAdmin() {
return this.authUser.role.name == 'admin'
},
in ToolBaar component (and remove from NavBar)
<script>
import { mapGetters } from 'vuex'
export default {
methods: {
toggleDrawer () {
this.$emit('toggleDrawer')
},
logout() {
this.$store.dispatch('logout')
}
},
computed: {
...mapGetters([
'loggedIn',
'authUser'
]),
fullName() {
return this.authUser.first_name + ' ' + this.authUser.last_name
},
isAdmin() {
return this.authUser.role.name == 'admin'
}
},
}
</script>
Then it work good, without any error, so i dont know what is the issue here, in one component code work good, and in another it doesnt, also if i add it in MainLayout component and pass isAdmin as props then it also work. Help me pls fix this.
Also, i dispatch user in router hook
router.beforeEach(async(to, from, next) => {
const needAuth = to.matched.some(record => record.meta.auth)
function redirectToLogin() {
next({
path: '/login',
query: { redirect: to.fullPath },
})
}
if (!hasToken() && needAuth) {
return redirectToLogin()
}
if (hasToken() && !store.getters.loggedIn) {
try {
const user = await store.dispatch('getUser')
if (!user) {
return redirectToLogin()
}
} catch(e) {}
}
next()
})
You should guard your access of authUser with loggedIn. For example
isAdmin() {
return this.loggedIn && this.authUser.role.name == 'admin'
}

Correct way to cache data in vuex

I am trying to asynchronously load data into vuex that is static but is used by multiple routes.I only want to fetch the data once and only when a route that needs it is visited. This is what I'm currently doing but I'm not sure if this is the correct convention or if there is a better/more Vueish way.
// store.js
export default new Vuex.Store({
state: {
_myData: null,
},
getters: {
myData: (state) => new Promise((resolve,reject) => {
if(state._myData){
resolve(state._myData);
} else {
axios.get('http://myData.com/')
.then(myData => {
state._myData = myData;
resolve(state._myData);
});
}
})
}
});
// ProfilePage.vue
<template>
<div>{{myData}}</div>
</template>
<script>
export default {
data() {
return {
myData:null
}
},
async created(){
this.myData = await this.$store.getters.myData;
}
}
</script>
// AboutPage.vue
<template>
<div>{{myData}}</div>
</template>
<script>
export default {
data() {
return {
myData:null
}
},
async created(){
this.myData = await this.$store.getters.myData;
}
}
</script>
There is a correct way to do what you want but it is not the way you are doing it. Vue is quite strict on "Do not mutate vuex store state outside mutation handlers."
This means you should only alter the store state through a mutation, then use your getter only to get the data. You should also use an action to commit the mutation. So for what you are trying to do you should try it like this.
// AnyPage.vue
<template>
<div>{{myData}}</div>
</template>
<script>
export default {
data() {
return {
myData:null
}
},
async created(){
if(this.$store.state._myData === null) {
await this.$store.dispatch('getData')
}
this.myData = this.$store.getters.myData;
}
}
</script>
then in your store:
// store.js
export default new Vuex.Store({
state: {
_myData: null,
},
getters: {
myData: (state) => state._myData,
}
mutations: {
SET_DATA(state, data) {
state._myData = data
}
}
actions: {
getData({ context }){
axios.get('http://myData.com/')
.then(res => {
context.commit('SET_DATA', res)
})
}
}
}
});
You should read up in the docs which covers it all pretty well.
Action handlers receive a context object which exposes the same set of methods/properties on the store instance, so you can call context.commit to commit a mutation, or access the state and getters via context.state and context.getters.
https://vuex.vuejs.org/guide/actions.html
try this:
// AnyPage.vue
<template>
<div>{{myData}}</div>
</template>
<script>
export default {
computed: {
myData () {
return this.$store.state.myData
}
},
mounted () {
this.$store.dispatch('getData')
}
}
</script>
in store file:
// store.js
export default new Vuex.Store({
state: {
myData: null,
},
mutations: {
SET_DATA(state, data) {
state.myData = data
}
}
actions: {
getData({ context }){
if (context.state.myData === null) {
axios.get('http://myData.com/')
.then(res => {
context.commit('SET_DATA', res)
})
}
}
}
}
});