What is local storage? How we can store data at client without a database?
Hey there.
This will be my first post on medium.com. I will share the things that I found interesting and learnt through my learning process of frontend development tools and techniques.
First topic will be local storage. Every frontend developer have heard that term but as I see in youtube community and the other places, very few people use this Javascript & HTML5 technology that allows us to store data in the storage of the browser that we use.
So how that works?
It works with the DOM (document object model) and javascript. It’s an in-built property of javascript and it stores data in the client-side browser storage. For small projects, we don’t need a database or backend to create an app. Let’s see how we can use it.
Let’s create a simple HTML page and add our javascript file into it.
Now, let’s jump into our app.js file. Look at methods of localstorage object:
Local storage works with good old “key:value” methodology. We give a key to it and store data that binded to that key (strings or stringified).
clear() : Clears every key:value pairs if there is any.
getItem(key): Gets us the item that the key we passed holds in our storage.
length: Total Item amount of our localstorage.
removeItem(key): Removes only items that the key we passed holds.
setItem(key,value): Sets a key that holds the value we passed in local storage. We can define everything as values which is in JSON/stringified form. Because localStorage object works with string.
Let’s set different values in our storage with a button to see how that stores the data.
And after that, we should see them in our application/localstorage/:ip section.
Now, we need to get them with javascript. The method we need is getItem. First, let’s see in console to see if we are getting the true items. I will add 3 additional button functions for each item in the storage.
If we click the buttons and see the results in console, it will look like this:
We can show them in the dom as we want. We just need to put those in the div that has root “id”.
And this is pretty much everything about local storage. You can play with it storing todo object in an array in the local storage and mapping them in the “virtual” dom. They all will be permanent until you delete them or clear the data of your browser.
Thank you all for reading my article about local storage and how to use it.