1

Im not sure If I am doing something wrong or if I have a typo somewhere, but I am trying to compare dates in a vue project but the value I pull from my local storage always returns null even when I can see the value clearly exists when I check my local storage. so here is the set up.

after making a request I set the expires date in local storage like so

retrieveToken({ commit }, credentials) {

      return new Promise((resolve, reject) => {
          axios.post('/login', {
              username: credentials.username,
              password: credentials.password,
          })
          .then(response => {
              const token = response.data.access_token
              const date = new Date(moment().add(30, 'seconds').toDate());
              localStorage.setItem('expires_on', date)
              localStorage.setItem('access_token', token)
              resolve(response)
          })
          .catch(error => {
              console.log(error.response.data)
              reject(error)
          })
      })
    },

I can then see that the expires on has been placed in my local storage enter image description here

I then want to use a getter to retrieve that value like so

tokenExpires() {
      return localStorage.getItem('expires_on')
    },

So i can use like this

computed: {
        ...mapGetters(['tokenExpires']),
    },
methods: {
     destroySessionIfTokenIsExpired() {
            const current = new Date(moment())
            const expires = this.tokenExpires
            const currentDate = moment(current).format('YYYYMMDDHHMMSS')
            const expiresDate = moment(expires).format('YYYYMMDDHHMMSS')
                console.log(this.tokenExpires)
                console.log(expiresDate)
            if(currentDate >= expiresDate) {
                this.$store.dispatch('destroyToken')
                .then(() => {
                    this.$router.push('/login')
                    alert('Your Session Has Expired, Please Log Back In')
                })
            } else return;
        }
       }

but when I run this method and console.log(this.tokenExpires) it returns null and I am not sure why. If anybody can see what I am doing wrong please let me know!!

*Update, my issue is that I am trying to watch the routes and run a comparison of timestamps to see if the session is still valid but as pointed out, the getter does not have enough time to compute the value before the method runs, so any suggestions on how I could get around that would be awesome. here is the route watch method

watch: {
        '$route': function(to, from) {
            this.destroySessionIfTokenIsExpired()
        }
    },
TJ Weems
  • 1,086
  • 3
  • 21
  • 37
  • When do you call `retrieveToken`? It's likely that the `expires_on` is not available yet when `tokenExpires` property is being computed, because `retrieveToken` have not gotten result back from server yet. Besides, `localStorage` is not reactive, so it won't trigger Vue's recalculation. – yqlim Jan 01 '19 at 16:21
  • @YongQuan, I see what your saying. Is there another way I could pull the value from localStorage without using a getter? if I refresh the page, it gives it enough time to get `tokenExpires` but I am also watching the routes as well which is where I am running into a problem. I will post my route watch method – TJ Weems Jan 01 '19 at 16:26
  • 1
    why not just simple `const expires = localStorage.getItem('expires_on')` in your `destroySessionIfTokenIsExpired` function? – yqlim Jan 01 '19 at 16:29
  • @YongQuan Ill give it a shot – TJ Weems Jan 01 '19 at 16:30
  • maybe [this](https://stackoverflow.com/questions/41851711/vuex-store-properties-not-reactive-when-using-computed-property) can give you another perspective. – yqlim Jan 01 '19 at 16:33

1 Answers1

0

thanks to @YongQuan I have this solution.

methods: {
        ...mapActions(['destroyToken']),
        destroySessionIfTokenIsExpired() {
            const expiresOn = localStorage.getItem('expires_on')
            const expiresDate = moment(expiresOn).format('YYYYMMDDHHMMSS')
            if(expiresOn == null) return;
            const current = new Date(moment())
            const currentDate = moment(current).format('YYYYMMDDHHMMSS')
            if(currentDate >= expiresDate) {
                this.$store.dispatch('destroyToken')
                this.$router.push('/login')
            } else return;
        }
    },
    watch: {
        '$route': function(to, from) {
            this.destroySessionIfTokenIsExpired()
        }
    },

Instead of using a getter I just set the `localStorage.getItem('expires_on') to a variable inside the method. Thanks @YongQuan

TJ Weems
  • 1,086
  • 3
  • 21
  • 37