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