rhythmo
rhythmo

Reputation: 949

How to set a watch property for current time and initiate an action in Vue js

I need to initiate an action when the current time exceeds a pre-set timestamp. The user needs to be logged out when the token expiry time is exceeded.

Here is a computed property currentTime defined

computed: {
  currentTime() {
    return Date.now();
  },
}

Here is the code for watcher for currentTime

watch: {

  async currentTime(newValue, oldValue) {
    // Log user out when current time exceeds the token expiry time
    // Getting token ExpiryTime
    if (localStorage.getItem("scatTokenExpiryTime")) {
      const tokenExpiryTime = localStorage.getItem("scatTokenExpiryTime");
      const timeRemainingInMinutes = moment.duration(
        tokenExpiryTime - newValue,
        "millisecond"
      ).asMinutes;

      // Logging out user
      if (newValue > tokenExpiryTime) {
        await this.$store.dispatch("logoutUser");
      } 
        //Dialogs for warning the user about auto-logout before 30, 5 and 1 min
       else if (timeRemainingInMinutes === 30) {
        this.handleDialog({
            timeRemainingInMinutes: timeRemainingInMinutes
          },
          "aboutToBeLoggedOut"
        );
      } else if (timeRemainingInMinutes === 5) {
        this.handleDialog({
            timeRemainingInMinutes: timeRemainingInMinutes
          },
          "aboutToBeLoggedOut"
        );
      } else if (timeRemainingInMinutes === 1) {
        this.handleDialog({
            timeRemainingInMinutes: timeRemainingInMinutes
          },
          "aboutToBeLoggedOut"
        );
      }
    }
  },
},

The problem is that the variable currentTime does not change and the watcher code is not executed. Any idea as to how the variable currentTime can be bound to the actual time.

How can I increment the variable currentTime with the actual time and watch for the point of time where I can apply the logic?

Upvotes: 0

Views: 3531

Answers (1)

Nikola Pavicevic
Nikola Pavicevic

Reputation: 23490

You can try to instead create data property currentTime:

data() {
  return {
    currentTime: 0
  }
},

Then on mounted hook set interval, update and watch currentTime from data:

mounted: function () {
  window.setInterval(() => {
    this.currentTime = new Date()
  }, 1000)
}, 

watch: {
  async currentTime(newValue, oldValue) {
    ...

Upvotes: 7

Related Questions