LocalStorage and SessionStorage helpers

Published:

#What do they do?

  • Adds a prefix to storage keys
  • Handle JSON encoding/decoding for simple JSON object storage
  • Handle Null values

#Local Storage Service

Data in localStorage does not expire.

class LocalStorageService {
private readonly storagePrefix = "scratchy__"
get<T>(key: string): T | null {
const item = window.localStorage.getItem(this.storagePrefix + key);
if (!item || item === "null") {
return null;
}
try {
return JSON.parse(item);
} catch (e) {
console.log(e);
}
return null;
}
set(key: string, value: any): boolean {
if (value === undefined) {
value = null;
} else {
value = JSON.stringify(value);
}
try {
window.localStorage.setItem(this.storagePrefix + key, value);
} catch (e) {
console.log(e);
}
return false;
}
remove(key: string) {
window.localStorage.removeItem(this.storagePrefix + key);
}
}
export default new LocalStorageService();

#Session Storage Service

Data in sessionStorage is cleared when the page session ends.

class SessionStorageService {
private readonly storagePrefix = "scratchy__"
get<T>(key: string): T | null {
const item = window.sessionStorage.getItem(this.storagePrefix + key);
if (!item || item === "null") {
return null;
}
try {
return JSON.parse(item);
} catch (e) {
console.log(e);
}
return null;
}
set(key: string, value: any): boolean {
if (value === undefined) {
value = null;
} else {
value = JSON.stringify(value);
}
try {
window.sessionStorage.setItem(this.storagePrefix + key, value);
} catch (e) {
console.log(e);
}
return false;
}
remove(key: string) {
window.sessionStorage.removeItem(this.storagePrefix + key);
}
}
export default new SessionStorageService();