I store Access token for authorization in javascript localStorage
. Every time when my frontend app loaded I want get this token for get user.
created() {
let access = localStorage.getItem('access')
console.log(access)
if (!access) {
console.log('access not exists')
} else {
console.log('access exists:', access)
}
}
But this token should has overwrited quite often. And when I clean this token because user logout I should get null value in Access. But chrome cache this value and 'if' block still get token like existed. This what i see in console:
How I can get uncached value? Or I should leave this. And it will disturb in production?
CodePudding user response:
Local Storage is not cached.
I assume the issue is the way how you clean local storage. I assume you are doing something like this: localStorage.setItem('access', undefined)
. This will set the local storage item to the string 'undefined'
, and if you do if (!access)
it will always return false. You currently cannot use undefined
, null
or true
/ false
in local storage, only strings. You can check the stored type by printing the returned type: console.log(typeof localStorage.getItem('access'))
, which should be string.
You have 2 options:
Remove the item completely from local storage
localStorage.removeItem('access')
Then you can use your current implementation, as local storage will return undefined
on localStorage.getItem('access')
.
Set an empty string and test for string length:
// "clean" your access
localStorage.setItem('access', '');
// Check if there is an access
const access = localStorage.getItem('access');
if (access && access.length > 0) {
console.log('access does exists')
} else {
console.log('access does NOT exists')
}