Day 22: Consolidation 5
Lesson 3: LocalStorage
LocalStorage lets us save data in a key/value store to get back later.
Saving data to LocalStorage
Data is saved as a string, so complex data needs to go through JSON.stringify
when saved. We save to LocalStorage with localStorage.setItem()
.
If you wanted to save an array of numbers then you would do this:
1let numbers = [3, 5, 7, 22, 4, 1]; 2localStorage.setItem("numbers", JSON.stringify(numbers));
Fetching data from LocalStorage
You can get saved data from LocalStorage with the localStorage.getItem()
function. If your data was run through JSON.stringify()
then you need to run it back through JSON.parse()
.
To read those numbers back you would do this:
1let numbersString = localStorage.getItem("numbers"); 2let numbers = JSON.parse(numbersString);
If that item doesn't exist then it will return null
so you should protect for that with either an if statement like:
1if (!numbers) { 2 numbers = []; // or the empty version of the type best for your data 3}
Alternatively with nullish coalescing:
1let numbers = JSON.parse(numbersString) ?? [];
Editing data in LocalStorage
Since data is stored as a string there is no way to directly edit it, you simply read the data out of LocalStorage, make the changes you want to make and then write it back to LocalStorage with the same item name. The complexity in editing is usually in keeping our UI up to data.
Deleting data from LocalStorage
Deleting data is very simple, you can delete the contents of a specific item with:
1localStorage.removeItem("numbers");
Or get rid of everything with:
1localStorage.clear();