What is Local Storage?
Local storage is an object in the DOM where you can store data, based on user behavior. When you store data on the localStorage
object (as opposed to sessionStorage
) it never expires. This is pretty handy since you can store something in the DOM (using the set
method), and get that same data (with a future get
method) to see if that user had been on the page yet.
The Use-Case
We will assume that there is a toast notification that is triggered when the custom function announceToast()
is called in a component. We'll also assume that it's recently been updated with new information.
In the app.component.ts
file, we've initialized a property (to the type of string) to hold a value representing the latest post:
export class AppComponent implements OnInit {
currentToast = 'Robots vs. Humans';
}
Now we can check to see if there's an object key in localStorage
called blog
(to the type of string) by checking when the component initializes:
export class AppComponent implements OnInit {
currentToast = 'Robots vs. Humans';
ngOnInit { // When the app initializes
// If the localStorage object key 'blog' has a value that does not match the currentToast string
if (localStorage.getItem('blog') !== this.currentToast) {
// Then we will clear localStorage altogether
localStorage.clear();
// We will trigger the new announcement toast
this.announceToast();
// And we'll set the 'blog' key to have the new current value
localStorage.setItem('blog', this.currentToast);
}
}
}
// If it does match, then we will do nothing and the value we set will continue to sit in localStorage under that key
This means, that when we eventually change the value of the currentToast property to something that is NOT 'Robots vs. Humans', the component will automatically evaluate this, clear the object and replace it with the new value (while triggering the new toast).
Now we only need to update one string to ensure that the user will see a new toast every time (and we don't pollute the localStorage object with old key value pairs).
Top comments (4)
Practical usecase :
Go to the browser and open mdn docs. You can see the website in normal mode. ( not in dark mode )
Now open
dev tools > application > storage > local storage
You can find something here!.. ( Key-val )
Now turn on the night mode observe the change in the local storage....
Also you can close the tab and revisit the mdn docs now you can see the website is in dark mode it is because of localstorage.
For people reading this, you can't store objects in local storage so you need to turn it to a string using JSON.stringify() then save it
Explicitly, localStorage can only store a string value. So, if you want to store an Object then you need to serialize it using JSON.stringify() and deserialize it using JSON.parse() in order to use the Object.
Hexcellent.