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
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()
}
},