2
votes

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.

1
Is state.activated initially set to true?Riddhi
nope, it is set to false initially.Rox
can you provide the code where you access the store?Sebastian
ok will add in the main questionRox
First of all you are using getters wrong. If getter doesn't do anything but is just passing data from state just use store.state.activated.Adam Orlov

1 Answers

1
votes

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.