Session Storage Methods with Expiry

We often need to cache the data in sessionStorage with an expiration timeout. 
Session Storage doesn't provide an expiration which is the case with cookies 

 As cookies allows only 4-5kb of datastorage. sessionStorage allows approx. 5MB of data storage.

 Below are some handy method for session storage with expiration.
function sessionGet(key: string) {
const stringValue = window.sessionStorage.getItem(key)
if (stringValue !== null) {
const value = JSON.parse(stringValue)
const expirationDate = new Date(value.expirationDate)
if (expirationDate > new Date()) {
return value.value
} else {
window.sessionStorage.removeItem(key)
}
}
return null
}
// add into session
// eslint-disable-next-line
function sessionSet(key: string, value: any, expirationInMin = 10) {
const expirationDate = new Date(new Date().getTime() + (60000 * expirationInMin))
const newValue = {
value: value,
expirationDate: expirationDate.toISOString()
}
window.sessionStorage.setItem(key, JSON.stringify(newValue))
}

Comments

Popular posts from this blog

Install Node.js without admin rights

Create a lean React Solution using Typescript