🌳Say goodbye to LocalStorage 🚀

edisonpappi

Edison Augusthy

Posted on September 1, 2020

🌳Say goodbye to LocalStorage 🚀

Alt Text

Being a front-end developer one of the common things that we wanted is to store and share data in the client browser, And most of us really rely on local storage. So what is localStorage..?
according to MDN:

The localStorage provides mechanisms by which browsers can store key/value pairs, in a much more intuitive fashion than using cookies. data stored in localStorage has no expiration time. Data in a localStorage object created in a "private browsing" or "incognito" session is cleared when the last "private" tab is closed.

So the data stored in localStorage is specific to the protocol of the page. In particular, data stored by a script on a site accessed with HTTP (e.g., http://example.com) is put in a different localStorage object from the same site accessed with HTTPS (e.g., https://example.com).

The keys and the values are always in the UTF-16 DOMString format, which uses two bytes per character. As with objects, integer keys are automatically converted to strings.

So what are localStorage disadvantages..?

  • data stored in localStorage has no expiration time
  • localStorage will be available for any tab or window in the browser,
  • Have to constantly keep back up of data to prevent loss
  • The user is completely responsible for the safety of the data
  • Takes up more storage space if you store locally

Switching to session storage

Window.sessionStorage is a better alternative option for localStorage.
A page session lasts only as long as the browser tab is open, and it will survive over page reloads and restores. But opening a page in a new tab or window will create a new session. And we have a storage limit is larger than a cookie (at most 5MB)

Using Session storage

setting data

We can store data using setItem method.
syntax :



sessionStorage.setItem('key', 'Value');


Enter fullscreen mode Exit fullscreen mode

the above code will add the given key-value pair to session storage.
EG:Alt Text

so the session storage now has data with key MyCat

Alt Text

Getting data

We can get data using the getItem method.
syntax :




sessionStorage.getItem("key")



Enter fullscreen mode Exit fullscreen mode

the above code will return data of that key from session storage.
EG: Alt Text

Removing Data

We can remove data using removeItem or clearmethod.
syntax :



sessionStorage.removeItem("key")
sessionStorage.clear()


Enter fullscreen mode Exit fullscreen mode

removeItem will remove a specific key from session storage, whereas the clear method will clean up the entire session storage

💖 💪 🙅 🚩
edisonpappi
Edison Augusthy

Posted on September 1, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related