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

Web Storage

Lesson Objectives

  1. Describe web storage
  2. Differentiate between localStorage and sessionStorage
  3. View storage in dev tools
  4. Set an item
  5. Get an item
  6. Remove an item
  7. Clear the storage
  8. Store objects/arrays
  9. 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

  1. Open up dev tools and click on "Application"

  2. Expand Local Storage and Session Storage

  3. 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'));