How to update state in a component when the value changed at vuex store?

Viewed 4145

In vuex store I have this mutations which receives msg from one component and is to show/hide prompt message at another component (Like You are logged in propmpt after successful login) :

setPromptMsg: function (state, msg) {
    state.showPromptMsg = true;
    state.promptMsg = msg;
        function sleep (time) {
        return new Promise((resolve) => setTimeout(resolve, time));
      }                           
     sleep(3000).then(() => {
          store.showPromptMsg = false;
          state.promptMsg = '';
          console.log('show message set to false');
      });
},

In the compoenet, I receive showPromptMsg from the store as a computed property:

computed: {
    showPromptMsg () {
        return this.$store.state.showPromptMsg;
    },
    promptMsg () {
    return this.$store.state.promptMsg;
    }
}

The show/hide prompt message in the template:

   <div v-show="showPromptMsg">
      <div class="text-center" >
         <strong> {{promptMsg}} </strong>
      </div>
  </div>

The problem is that when the prompt is timedout, i.e. showPromptMsg is set to false at the store, the change is not reflected into the component, so the notification box does not disappear.

I'm wondering what is the idiomatic way to resolve this problem?

2 Answers

The code is setting

store.showPromptMsg = false;

I expect you want

state.showPromptMsg = false;

In your NotificationBarComponent.vue template:

<div>
    <div class="text-center" >
       <strong> {{ message }} </strong>
    </div>
</div>

In your NotificationBarComponent.vue component definition add a prop to pass custom message to display and on mounted start the timeout to hide the notification:

export.default {
    props: ['message'],
    mounted() {
        window.setTimeout(() => {
            this.$store.commit('handleMessageState', false)
        }, 3000);
    }   
};

in your store create a property to manage the notification display isNotificationBarDisplayed: false

handleMessageState(state, payload) {
    state.isNotificationBarDisplayed = payload;
}

anywhere you want to use it:

<notification-bar-component v-show="isNotificationBarDisplayed" message="Some message here"></notification-bar-component>

computed: {
    isNotificationBarDisplayed () {
        return this.$store.state.isNotificationBarDisplayed;
    },
}
Related