There are two types of storage you can use:
- Local storage: Data that persists even if you refresh the page or close the browser.
- Session storage: Data that will get cleared when the browser is closed.
Why Are Local Storage and Session Storage Useful?
So, if you’re building a static website you won’t need any back-end language or logic to store data. Also, your local storage provides 5MB of data storage, while you can only store a maximum of 4KB in a cookie.
A few technical things:
- You can set key: value pairs.
- You can only store strings.
- You can store arrays and objects, but you have to turn them into strings first, using a method called
JSON.parse(). More on this later.
These are the methods for local storage:
Setting data into local storage:
Setting data into session storage:
If you go into your console in your browser (
CMD+Option+J) and go into the Application tab you can see your data.
get from storage:
remove from storage:
clear all from storage:
Example: Saving a Task
Quick example. If you had a form for, let’s say, a task list, and you wanted to save the task the user submits, you could do something like this:
Find your form input:
‘submit’ to form input:
Grab the form’s input
Here is the somewhat tricky part. If we want to store multiple tasks from the user, we need to create an array of tasks and store that as a string.
- First, we need to check to see if there is something in local storage and, if there is, pull it out and add to. And if not, set an empty array.
2. Now we want to wrap our
localStorage.getItem(‘tasks’); in a method called
JSON.parse(). Then, we want to pass our
task variable into our
3. We will convert tasks back into a string because we can only store strings in our local and session storage.
4. Now, if we want to iterate through it and use a
forEach(), we have to parse it back or we’ll get
forEach is not a function error because tasks is an array — we pulled it out from local storage which only stores strings.
Thanks for reading!