1

We are trying to detect whether a person is logged in or not using the vuex store state: loggedIn. When I call the API service from the action it calls the mutation after successful login and changes the data in the state:

loginSuccess(state, accessToken) {
    state.accessToken = accessToken;
    state.authenticating = false;
    state.loggedIn = true;
    console.log(state.loggedIn);
  }

The console.log() shows the value, so the mutation is working.

In my other component, I use a computed property to watch for changes in the store using ...mapState() and bound the property in the template view:

computed: { 
    ...mapState('authStore',['loggedIn' ]);
  }

But the view never gets updated based on the computed property. I checked using the Vue dev tools in the console. It shows the state changes.

I have initialized the state.

export const states = {
  loggedIn: false
};

I have tried to call the state directly.

this.$store.state.authStore.loggedIn;

I have tried different approaches.

...mapState('authStore', { logging:'loggedIn' });
//or
...mapState('authStore',['loggedIn' ]);

also, tried watch: {} hook but not working.

Interestingly though, the state's getter always shows undefined, but the state property changes in the dev tools.

Cannot figure out what is wrong or how to move further.

here is the screenshot of devtools state after successful login:

after login success

1 Answers1

2

This catches my eye:

export const states = {
  loggedIn: false
};

My suspicion is that you're then trying to use it something like this:

const store = {
  states,
  mutations,
  actions,
  getters
}

This won't work because it needs to be called state and not states. The result will be that loggedIn is unreactive and has an initial value of undefined. Any computed properties, including the store's getter, will not be refreshed when the value changes.

Whether my theory is right or not, I suggest adding console.log(state.loggedIn); to the beginning of loginSucess to confirm the state prior to the mutation.

skirtle
  • 27,868
  • 4
  • 42
  • 57
  • Thanks a lot @Skirtle for your solution.we stuck for 2 days for this . :D – Didarul Alam Rahat Jun 27 '19 at 16:47
  • you have a really sharp eye! thanks for your reply. missed that myself too. – Rakibul Haq Jun 27 '19 at 17:10
  • It comes to my attention that `state` should be singular: https://vuex.vuejs.org/api/#state. And if you are using SSR (say, with Nuxt), you also wan't your state be a function that returns an object – Paul Melero Sep 30 '19 at 12:41
  • @PaulMelero I'm not sure what point you're making. My answer already explains that it is `state` and not `states`. As for SSR, that doesn't seem relevant to the question that was asked. – skirtle Sep 30 '19 at 15:20
  • You're right. I didn't see that on your answer. The SSR part maight be useful for other folks. – Paul Melero Oct 03 '19 at 09:51