DEV Community

Cover image for Simple Javascript Modules - Local Storage Module
Sooraj (PS)
Sooraj (PS)

Posted on • Edited on

Simple Javascript Modules - Local Storage Module

Working as a web developer I work on the client side dealing with lots of continuous data from the server. All though it is a good practice to not store data on the client side, there will be many cases where we want to store some information on the client for faster access. A good use case would be the app theme theme: "light" or theme: "dark".

So that is where we can use Local Storage of the Browser using the 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.

Local Storage Description

As you can see here in the code below, I have added all the things that we mostly do with local storage. Usually all these functions are separately written in a utility module. But here I have kept it separately so that in any case of change, we just replace the functions inside the module and our application code remains untouched. 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;
Enter fullscreen mode Exit fullscreen mode

I have written a total of 5 properties on my module here which will use the window.localStorage API and are as follows.

1.exists - This contains a boolean value that checks if the current browser supports local storage or not.

2.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".

3.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.

For example running this =>

Storage.add("myKey", { name: "Sooraj" })
Enter fullscreen mode Exit fullscreen mode

Will add this under the key called "myKey"
Added Local Storage

4.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.

5.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.

Well, this is my Storage module. Hope you guys found it useful. Go ahead and try it out...

Top comments (14)

Collapse
 
qm3ster profile image
Mihail Malo • Edited

I'm sorry, but this code makes no sense and is frankly confusing and dangerous.
It doesn't really add any convenience over just using window.localStorage directly, besides the JSON conversion.
This can be achieved with just

export class JSONStorage {
  constructor(storage) {
    if (!storage || typeof storage !== "object")
      throw new Error(`Expected a Storage object, got ${storage}`)
    this.storage = storage
  }
  set(k, v) {
    const str = JSON.stringify(v)
    if (typeof str === "undefined")
      return this.storage.removeItem(k)
    this.storage.setItem(k, v)
  }
  get(k) {
    const str = this.storage.getItem(k)
    // we return `undefined` instead of `null`, so that we can differentiate between the cases when the key doesn't exist vs when the value is a JSON-serialized `"null"`
    if (str === null) return
    return JSON.parse(str)
  }
  remove(k) {
    this.storage.removeItem(k)
  }
}
Enter fullscreen mode Exit fullscreen mode

you can try it as follows

const a = new JSONStorage(window.localStorage)
const b = new JSONStorage(window.sessionStorage)
a.set("1", 1)
b.set("1", 2)
// notice that keys are coerced to string automatically, and we get back deserialized numbers, not strings
a.get(1) // 1
b.get(1) // 2
Enter fullscreen mode Exit fullscreen mode

Instead, the provided code:

  1. checks if localStorage is supported on every action, instead of just once.
  2. calls .getItem(key) twice, which might be the most expensive operation here, short of setItem
  3. similarly, calls getItem before removeItem
  4. since !"" is true, empty values (if created outside this interface) will never be removed!
  5. uses a mutable field data on the singleton object instead of a local variable. This data never needs to survive beyond a function call, and is being reused by all accesses to Storage.
  6. constructs a {key, data} object with the function's arguments, which will never be used and doesn't offer any ergonomic benefit.
  7. declares a function to just set null to this.data.
  8. on most error conditions (such as passing a number as key, because numbers don't have .length), randomly returns the contents of this.data, which will always be null because every method, even remove that doesn't use it first calls clearData. This is confusing, since the standard getItem returns null for missing key, and "null" is a valid JSON string.
  9. makes an object instance named Storage to then just export it as default, instead of exporting the individual functions, avoiding a layer of indentation.

PS: Keep in mind, my code still doesn't prevent you from calling, say, b.set() which would create a undefined => undefined entry, which would cause a JSON SyntaxError when calling b.get(), nor does it exhaustively check for the storage object passed to the constructor having the necessary methods.

Edit: The former is quite serious, so I fixed it now. This now removes the key, so setting a value of undefined and then getting it will, in fact, return undefined

Collapse
 
soorajsnblaze333 profile image
Sooraj (PS)

Thank you for the informative points :)

Collapse
 
johnsmi24031868 profile image
Info Comment hidden by post author - thread only accessible via permalink
John Smith

No one is holding you at gunpoint forcing you to read articles. If you don't like the content, leave the article and move on. I don't see how it's a bad thing for developers to be improving their skills (both communication and coding) by writing articles anywhere they want to. Frequently English is not someone's first language, and writing articles about what you're learning is a great way to get feedback and practice, and the urge to teach other people skills you've learned should be applauded.

I've always thought it's quite interesting to watch people gain new skills and learn new things, considering all of us do that on a regular basis.

Perhaps it would be more productive to offer constructive feedback about particular things authors could improve upon rather than criticizing an article as a whole. In my experience, that helps developers learn to improve, as opposed to sarcastic and generalized criticism, which just discourages authors from making attempts and continuing to improve in the future. Practice makes perfect, and writing an article is a great way to work on communication skills.

Collapse
 
soorajsnblaze333 profile image
Sooraj (PS)

Thank you John :)

Collapse
 
soorajsnblaze333 profile image
Info Comment hidden by post author - thread only accessible via permalink
Sooraj (PS) • Edited

The reason for mentioning "Local Storage" is for beginner developers and developers working on other languages to understand what the word means first. No new developer will right away know what "localStorage" or why the word/function is spelt like that or what it does when they jump into javascript. If I come from other language I would question why localstorage is written as localStorage.

And also I have mentioned "Local Storage" only in a context to understand it is and not in code. So please read the article completely before coming to a conclusion.

Collapse
 
vuchuru27916 profile image
Preethi Vuchuru27916

As a newbie to the concept of Local storage in JavaScript, your comments on the code and explanation made it simple for me to understand. Will be using this to create something in Javascript.

Collapse
 
soorajsnblaze333 profile image
Sooraj (PS)

Thank you so much :)

Collapse
 
manikandanm1757 profile image
manikandanm1757

Handling of data in local storage explained well, Thanks.

add method will not work properly for falsy values like 0, false, null

Collapse
 
soorajsnblaze333 profile image
Sooraj (PS)

Thanks for pointing it out :) I will add a check for it

Collapse
 
upupkenchoong profile image
Ken Choong

The code of localStorage is super lit, literally on fire

Collapse
 
soorajsnblaze333 profile image
Sooraj (PS)

Thank you Ken, I am glad you like it :)

Collapse
 
ajozz13 profile image
Alberto Ochoa

Awesome

Collapse
 
andreseduardop profile image
andreseduardop

Excellent. Thanks for sharing. I look forward to more modules. ;)

Collapse
 
soorajsnblaze333 profile image
Sooraj (PS)

Sure will be adding mode modules :)

Some comments have been hidden by the post's author - find out more