Hi ๐, back again with another topic on the Learning JavaScript series I am doing and this time I would be discussing Local and Session Storage with practical implementations.
Local Storage vs Session Storage
The difference between this two is that Local Storage data persist(continues to exsist ) in the browser until the user manually clears their cache while for Session Storage data only exsist until the browser is closed.
Both Local and Session Storage are part of the window object. It has methods namely getItem(), setItem(), clear() and removeItem() etc. In this part series we would be looking at how these work.
//The lines below sets the local storage to hold data for name and age
localStorage.setItem("name", "Omotola");
localStorage.setItem("age", 100);
//Retrieves data from localStorage
let name = localStorage.getItem("name")
console.log(name);
// At this point > Left Click in your broswer
// > Click on inspect
// > Click on Application
// > On the left hand side you would see Local storage
// > Expand it and click to see your data stored
//To remove particular data
localStorage.removeItem("name")
//To clear everything in storage
localStorage.clear()
A usecase for Local Storage.
Whatever datatype that is stored in your local storage by default the browser saves it as a string. So to retrieve the data, it would need to be changed back to the usable datatype. A good usecase is giving your users the ability to bookmark an article on your blog so they can come back to it at a later date. On the blog bitsOfCode by Ire Aderinokun, a woman in tech I admire, this example is implemented where users can bookmark articles for a later date.
When the user clicks on the bookmark button an object with the uri path and title is created and pushed to an array which is then stored in local storage under the key name articles. If the user clicks this bookmark again the article data is removed from storage. Brilliant! All other prerequisites being coded, the code for implementing this might look something like this.
localStorage.setItem
document.querySelector(".bookmark-button").addEventListener('click', function(e){
//Gets the innerText of the H1 element
const title = document.querySelector(".header-title").innerText;
//Gets the baseURI and splits it using the delimiter / now the path value is path[3]
const path = document.querySelector(".post__title").baseURI.split(/(?=\/)/);
let articles;
if(localStorage.getItem('articles') === null){
articles = []
}
else{
//Parsing because we need a JSON object to work with
articles = JSON.parse(localStorage.getItem("articles"));
}
//JSON.strigify because data is stored as strings in local storage
articles.push({path : path[3], title : title});
localStorage.setItem("articles", JSON.stringify(articles));
})
In this code we can see that the bookmark-button is selected using the query selector and once the user clicks on the button the function is called which
- Stores the value of the title and an array of the URI split by the delimiter that is "/" the Regex passed to string helps add the delimeter to the split strings
- The code then checks if there is something with that keyname in local storage, if there isnt then the variable articles is set to an empty array. if there is then we parse the values in storage and assign it to the articles variable.
- We then push the new article as an object with keys names path and tiles and assign them their respective values.
- The array is then set back to localStorage with the new addition.
localStorage.getItem
I would be using localStorage.getItem to remove a single bookmarked article from our stored array of objects instead of localStorage.removeItem because what localStorage.removeItem will do is, it will remove the whole array and not a specific article. See example of localStorage.removeItem above.
So instead the code will look like this
//If the user clicks the bookmark button again
document.querySelector(".saved").addEventListener('click', function(){
const articles = JSON.parse(localStorage.getItem("articles"));
const title = document.querySelector(".header-title").innerText;
const newArticles = articles.filter(article => article.title !== title)
//set the data in locaStorage.
localStorage.setItem("articles", JSON.stringify(newArticles));
})
Here we have implemented what it would look like if the user tries to remove an article from localStorage.
- First we load the articles from localStorage
- Select the article you want to remove from localStorage
- If the article name does not match the article title we selected earlier we want to save it in the newArray
- The newArray with the remove article is then set in localStorage.
PS: If you thought about using the filter method instead of looping the array hi-5 โ you are learning!
If the user then navigates to the page where they can view all bookmarks the code to load this should look like this
document.addEventListener("DOMContentLoaded", getBookmarkArticles);
const bookmarkList = document.querySelector(".bookmark-list");
function getBookmarkArticles(){
let articles;
if(localStorage.getItem('articles') === null){
articles = []
}
else{
articles = JSON.parse(localStorage.getItem("articles"));
}
articles.forEach(function(article){
const link = document.createElement("a");
const li = document.createElement("li");
li.className = "bookmark-item";
li.appendChild(document.createTextNode(article.title));
link.href = `https://bitsofco.de${article.path}`
link.appendChild(li);
//append child to the ul list
bookmarkList.appendChild(link);
})
}
localStorage.removeItem and localStorage.clear
And finally if the user wants to clear their bookmarks it is safer to use
document.querySelector("clear-bookmark").addEventListener("click", function(){
localStorage.removeItem("articles");
})
than
document.querySelector("clear-bookmark").addEventListener("click", function(){
localStorage.clear();
})
This is because the second example will compelely clear everything in localStorage. Great! Remember the same functions are available with session storage as well, they just expire once the browser is closed. A practical example of using sessions storage is saving a users login credentials during their session in the web browser tab. So instead of the user having to login again when they open another tab the session just persist
I hope this was helpful. Thank you! React to this post, or comment down below your thoughts I would like to hear from you.
If you have missed the other post in this series here is a link to them below