Skip to content

Instantly share code, notes, and snippets.

@mario-subo
Last active July 5, 2022 16:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mario-subo/53a2a89c09719a34b62a0f01b5a30245 to your computer and use it in GitHub Desktop.
Save mario-subo/53a2a89c09719a34b62a0f01b5a30245 to your computer and use it in GitHub Desktop.
simple JS local storage utility
export const setLocalStorage = (key: string, value: any) => {
if (typeof key !== "string") {
throw new Error(`Error in localStorage: key ${key} must be of type string but is ${typeof key}`);
}
const typeOfValue = typeof value;
console.log(`localStorage: about to save value of type ${typeOfValue} for key ${key}`);
let valueToStore;
switch (typeOfValue) {
case "string":
case "number":
case "boolean":
valueToStore = value.toString();
break;
case "object":
valueToStore = JSON.stringify(value);
break;
default:
throw new Error(`Error in localStorage: tried to save value ${value} of type ${typeOfValue} for key ${key}`);
}
try {
window.localStorage.setItem(key, valueToStore);
} catch (error) {
console.error(error);
}
};
export const getLocalStorage = (key: string, defaultValue?: any) => {
if (typeof key !== "string") {
throw new Error(`Error in localStorage: key ${key} must be of type string but is ${typeof key}`);
}
const value = window.localStorage.getItem(key);
if (value) {
try {
const obj = JSON.parse(value);
return obj;
} catch (error) {
const isnum = /^\d+$/.test(value);
if (isnum) {
return parseInt(value, 10);
}
if (value === "true") {
return true;
}
if (value === "false") {
return false;
}
return value;
}
} else {
if (defaultValue) {
console.warn("localStorage: Returning default value");
return defaultValue;
}
console.warn(`Warning in localStorage: Cannot find value for key ${key} and no default value provided, returning null`);
return null;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment