25
loading...
This website collects cookies to deliver better user experience
theme: "light"
or theme: "dark"
.window.localStorage API
. It is a free storage space available for almost all major browsers and we can save a considerable amount of safe data for quick use in our application. It can be found on almost all major browsers. You can view, modify or delete the local storage data under the Application Tab in your browser followed by Local Storage and clicking your domain.The whole point of writing these functions together as a module is to keep the code clean, crisp and understandable.
// A localStorage object for performing crud operations on window.localStorage with ease
const Storage = {
// check if local storage is supported on browser
exists: (window.localStorage !== undefined),
// get the local storage data of the key
get(key) {
if (!this.exists) return;
const data = window.localStorage.getItem(key);
if (!data) return;
return JSON.parse(data);
},
// add a new data to given key in local storage
add(key, data) {
if (!this.exists) return;
window.localStorage.setItem(key, JSON.stringify(data));
},
// remove the data by the given key from local storage
remove(key) {
if (!this.exists) return;
window.localStorage.removeItem(key);
},
// wipe entire local storage of current domain
wipe() {
if (!this.exists) return;
window.localStorage.clear();
}
}
export default Storage;
window.localStorage API
and are as follows.exists
- This contains a boolean value that checks if the current browser supports local storage or not.get(key)
- This function is used to get the data that is associated with the key that is sent in the parameters. For example if get("name")
will get you the data that is saved under the name key in local storage. This function calls the window function called localStorage.getItem()
which takes 1 parameter "key".add(key, data)
- This function is used to add new data to the local storage. The key
attribute specifies to which key the data should be added to and the data
attribute contains the data to be added. This function calls the window function called localStorage.setItem()
which takes 2 parameters "key" and "data". It could be anything like a string, number, array, object etc.Storage.add("myKey", { name: "Sooraj" })
remove(key)
- This function is used to remove the data associated with the key that is sent in the parameters. This function calls the window function called localStorage.removeItem()
which takes 1 parameter "key". If remove("myKey")
is called the data that was added before would be cleared from the storage.wipe()
- This is a method I would not use that many times. This function calls the window function called localStorage.clear()
which takes no parameters. This function clears all the local storage data associated with the client on that domain.