localStorage.getItem() always returns null even when value exists
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()
}
},
vue.js local-storage
add a comment |
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()
}
},
vue.js local-storage
When do you callretrieveToken
? It's likely that theexpires_on
is not available yet whentokenExpires
property is being computed, becauseretrieveToken
have not gotten result back from server yet. Besides,localStorage
is not reactive, so it won't trigger Vue's recalculation.
– Yong Quan
Jan 1 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 gettokenExpires
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 1 at 16:26
1
why not just simpleconst expires = localStorage.getItem('expires_on')
in yourdestroySessionIfTokenIsExpired
function?
– Yong Quan
Jan 1 at 16:29
@YongQuan Ill give it a shot
– TJ Weems
Jan 1 at 16:30
maybe this can give you another perspective.
– Yong Quan
Jan 1 at 16:33
add a comment |
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()
}
},
vue.js local-storage
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()
}
},
vue.js local-storage
vue.js local-storage
edited Jan 1 at 16:29
TJ Weems
asked Jan 1 at 16:16


TJ WeemsTJ Weems
157110
157110
When do you callretrieveToken
? It's likely that theexpires_on
is not available yet whentokenExpires
property is being computed, becauseretrieveToken
have not gotten result back from server yet. Besides,localStorage
is not reactive, so it won't trigger Vue's recalculation.
– Yong Quan
Jan 1 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 gettokenExpires
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 1 at 16:26
1
why not just simpleconst expires = localStorage.getItem('expires_on')
in yourdestroySessionIfTokenIsExpired
function?
– Yong Quan
Jan 1 at 16:29
@YongQuan Ill give it a shot
– TJ Weems
Jan 1 at 16:30
maybe this can give you another perspective.
– Yong Quan
Jan 1 at 16:33
add a comment |
When do you callretrieveToken
? It's likely that theexpires_on
is not available yet whentokenExpires
property is being computed, becauseretrieveToken
have not gotten result back from server yet. Besides,localStorage
is not reactive, so it won't trigger Vue's recalculation.
– Yong Quan
Jan 1 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 gettokenExpires
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 1 at 16:26
1
why not just simpleconst expires = localStorage.getItem('expires_on')
in yourdestroySessionIfTokenIsExpired
function?
– Yong Quan
Jan 1 at 16:29
@YongQuan Ill give it a shot
– TJ Weems
Jan 1 at 16:30
maybe this can give you another perspective.
– Yong Quan
Jan 1 at 16:33
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.– Yong Quan
Jan 1 at 16:21
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.– Yong Quan
Jan 1 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 1 at 16:26
@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 1 at 16:26
1
1
why not just simple
const expires = localStorage.getItem('expires_on')
in your destroySessionIfTokenIsExpired
function?– Yong Quan
Jan 1 at 16:29
why not just simple
const expires = localStorage.getItem('expires_on')
in your destroySessionIfTokenIsExpired
function?– Yong Quan
Jan 1 at 16:29
@YongQuan Ill give it a shot
– TJ Weems
Jan 1 at 16:30
@YongQuan Ill give it a shot
– TJ Weems
Jan 1 at 16:30
maybe this can give you another perspective.
– Yong Quan
Jan 1 at 16:33
maybe this can give you another perspective.
– Yong Quan
Jan 1 at 16:33
add a comment |
1 Answer
1
active
oldest
votes
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
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53996986%2flocalstorage-getitem-always-returns-null-even-when-value-exists%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
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
add a comment |
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
add a comment |
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
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
answered Jan 1 at 17:09


TJ WeemsTJ Weems
157110
157110
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53996986%2flocalstorage-getitem-always-returns-null-even-when-value-exists%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
When do you call
retrieveToken
? It's likely that theexpires_on
is not available yet whentokenExpires
property is being computed, becauseretrieveToken
have not gotten result back from server yet. Besides,localStorage
is not reactive, so it won't trigger Vue's recalculation.– Yong Quan
Jan 1 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 1 at 16:26
1
why not just simple
const expires = localStorage.getItem('expires_on')
in yourdestroySessionIfTokenIsExpired
function?– Yong Quan
Jan 1 at 16:29
@YongQuan Ill give it a shot
– TJ Weems
Jan 1 at 16:30
maybe this can give you another perspective.
– Yong Quan
Jan 1 at 16:33