You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
2.1 KiB
2.1 KiB
Web Storage
Lesson Objectives
- Describe web storage
- Differentiate between localStorage and sessionStorage
- View storage in dev tools
- Set an item
- Get an item
- Remove an item
- Clear the storage
- Store objects/arrays
- Retrieve objects/arrays
Describe web storage
Web storage is like cookies, but it doesn't get transmitted to the server. It's more secure, more performant, and the storage limit is larger (5MB per origin).
The format is key value pairs, both of which are strings
Differentiate between localStorage and sessionStorage
- localStorage lives on until deleted
- sessionStorage ends when the user closes the window
View storage in dev tools
-
Open up dev tools and click on "Application"
-
Expand Local Storage and Session Storage
-
Click on one of the DBs to view its contents
Set an item
localStorage.setItem('foo', 'bar');
sessionStorage.setItem('age', 2); //note this will be converted to a string
Get an item
localStorage.getItem('foo'); //'bar'
sessionStorage.getItem('age'); //2 - note this is a string, even though, it was set as a number
Remove an item
localStorage.removeItem('foo');
sessionStorage.removeItem('age');
Clear the storage
localStorage.clear();
sessionStorage.clear();
Store objects/arrays
localStorage.setItem('myObj', {foo:'bar'});
This doesn't work:
Instead you have to convert objects and arrays into strings:
localStorage.setItem('myObj', JSON.stringify({foo:'bar'}));
localStorage.setItem('myArray', JSON.stringify([1,2,'apple']));
Retrieve objects/arrays
After, JSON.stringify(), the arrays/objects are stored in local/session storage as strings. To get them back into variables, use JSON.parse():
const myObj = JSON.parse(localStorage.getItem('myObj'));
const myArray = JSON.parse(localStorage.getItem('myArray'));




