Rox
Rox

Reputation: 361

Vuex store getter always returning false

I am new to Vue js, and also with Vuex. I am having trouble accessing store getters, enter image description here

You can see in getter, Activated is true, And In My getter in store.js is

 getters: {
loggedIn(state) {
  return state.token !== null
},
Activated(state) {
  return state.activated;
},

You can see state activated also is true, But when I access by

store.getters.Activated

It always return false, but When I access another getter logged in by same method in same function it gives the value true.

store.getters.loggedIn

Where I tried to access this in

router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
  if (!store.getters.loggedIn) {
    next({
      name: 'home',
    })
  } else {
    next()
  }
} 
else if (to.matched.some(record => record.meta.requiresActivation)) {
  debugger;
  if (store.getters.Activated===true) {
    next()
  } else {
    next({
      name: 'activate',
    })
  }
}
else if (to.matched.some(record => record.meta.requiresVisitor)) {
  if (store.getters.loggedIn) {
    next({
      name: 'activate',
    })
  } else {
    next()
  }
} else {
  next()
}

})

mutation in store js

mutations: {
updateFilter(state, filter) {
  state.filter = filter
},

retrieveToken(state, token) {
  state.token = token
},
CheckActivation(state, value) {
  state.activated = value
},
destroyToken(state) {
  state.token = null
}},

and actions

actions: {
CheckActivation(context){
  if(this.token===null){
    context.commit('CheckActivation', false)
    return false;
  }
  else{
    var settings = {
      "async": true,
      "crossDomain": true,
      "url": "http://vuejs.test/api/user",
      "method": "GET",
      "headers": {
        "Accept": "application/json",
        "Authorization": "Bearer "+ this.state.token,
        "cache-control": "no-cache"
      }
    }
    $.ajax(settings).done(function (response) {
      if(response.verified)
      context.commit('CheckActivation', true)
      else
      context.commit('CheckActivation', false)
    });
  }
},

Please Help.

Upvotes: 2

Views: 2079

Answers (1)

Riddhi
Riddhi

Reputation: 2244

So it's most probably because you would be accessing the store variable before it is set to true . For accurate solution please add code of mutation of above variable and method call.May be you will need to use async await in actions of store and in method call of vue file.

Upvotes: 1

Related Questions