VCF

Unit 7 · Data that lasts

localStorage only stores strings

Browser storage only holds text. Save a list with JSON.stringify(todos), and turn it back into a list with JSON.parse(...) when the page loads.

The mix-up

What people often think

“Storage can hold a list just like a variable can.”

What the tutor says

Browser storage only holds text. Turn the list into text with JSON.stringify(todos), and back into a list with JSON.parse.

What do you think store.getItem gives back if you save the list without stringify?

How it works

Saving is only half the job. When the page starts it is empty again, so read the saved text back with getItem, parse it, and render it.

Handle the first visit, when nothing has been saved yet: getItem returns null, so fall back to an empty list.

An example

What worksJavaScript
localStorage.setItem('todos', JSON.stringify(todos));

// on page load
todos = JSON.parse(localStorage.getItem('todos') ?? '[]');
render();
Stringify to save, parse to load.

Close cousins of this mix-up

The tutor watches for these in the same lesson.

  • “Once the list is saved, the page will remember it by itself.”

    Saving writes it down. When the page loads, loadTodos has to read it back with store.getItem, or the page starts empty again.

Practise it with a tutor watching

Why a database

Say where a piece of data should live: page memory, the browser, or a database on a server.

15 minutes See it Build it Break it Say it
Start the lesson

Free, no account needed.