# Local storage

  • Local storage allows developers to store and retrieve data in the browser
  • The stored data will not expire and will persist even if the user closed the browser window
  • Local storage is part of the Web storage API (opens new window)
  • Local storage stores a key/value combination inside the client's browser
  • The value can be any type of data (a string, a number, an array, a JSON object, ...), as long as you can convert it to a string
methode description
localStorage.setItem('key', 'value') save the key with his value to local storage
localStorage.getItem('key') retrieve the value from a specific key from local storage
localStorage.removeItem('key') remove the key from local storage
localStorage.clear() remove all keys from local storage
  • Because the value can only be a string, you will mostly have to convert your variables before storing them:
    • localStorage.setItem('key', JSON.stringify(<variable>))
    • let variable = JSON.parse(localStorage.getItem('key'))

# Examples

# Store form data

  • Saving form data is one of the most used features of local storage
  • In this example we the username and password on a login form, so it's already filled in the next time you open te page
  • Open es6/storage/login.html and es6/storage/login.js

# Shoppinglist

  • In this example, we introduce a new HTML property contenteditable (opens new window) e.g: <div contenteditable>milk</div>
  • This attribute allows us to edit the content of the element without the need for an additional input field
  • Open es6/storage/shopping.html and es6/storage/shopping.js

# Store accordion state (advanced)

  • Every main section inside this course has some kind of 'accordeon' tabs that contains some links to examples or exercises
  • The state of every tab (open or closed) is saved in local storage
  • Because the same logic is used in three different pages, we decided to work with a class
  • Open es6/index.html and js/classes/StoreTabs.js

# References

Last Updated: 3/11/2021, 2:26:59 PM