Didarul Alam Rahat
Didarul Alam Rahat

Reputation: 851

Computed Property does not get updated when state changes

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

Upvotes: 1

Views: 616

Answers (1)

skirtle
skirtle

Reputation: 29132

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.

Upvotes: 2

Related Questions