Overview
Let me share utility functions to parse data from local storage and set data to local storage.
Any advices to improve the functions, much appreciated 🙏
Parse local storage data
/*
* To get the value from local storage that matches the given key
* @param {string} key
* @returns The value of the key argument
*/
const parseLocalStorageJSON = (key) => {
if (!key || typeof key !== "string") {
throw new Error("Invalid key");
}
/**
* Handle non-string value with JSON.parse.
* Catch string value and return it
*/
try {
return JSON.parse(localStorage.getItem(key));
} catch {
return localStorage.getItem(key);
}
};
Set data to local storage
/**
* To set the key-value pair to local storage
* @param {string} key
* @param {any} value
* @returns N/A
*/
const setToLocalStorage = (key, value) => {
if (!key || typeof key !== "string") {
throw new Error("Invalid key");
}
if (typeof value === "object") {
localStorage.setItem(key, JSON.stringify(value));
} else {
localStorage.setItem(key, value);
}
};
Demo
On click of "Set&Parse" button, the above two functions are called.
The result can been seen,
- Set => in the devtool, local storage
- Parse => in the console
Top comments (0)