30 Days Of JavaScript

Day 19: LocalStorage

Lesson 3: Editing data in LocalStorage

Since data is saved in LocalStorage as strings there isn't really a way to edit it. Really what we do is read the data back, change it and save the data back.

Let's add a button to increase all the numbers by one. Add this to your HTML

1<button id="add-one">Add 1</button>

and this to your JavaScript

1const addButton = document.getElementById("add-one");
2addButton.onclick = () => {
3  const numbersString = localStorage.getItem("numbers");
4  const numbers = JSON.parse(numbersString) ?? [];
6  const increasedNumbers = numbers.map((number) => number + 1);
8  localStorage.setItem("numbers", JSON.stringify(increasedNumbers));
10  // delete the numbers from the DOM
11  while (ul.hasChildNodes()) {
12    ul.removeChild(ul.children[0]);
13  }
15  // add increased numbers to the DOM
16  increasedNumbers.forEach((number) => {
17    const li = document.createElement("li");
18    li.innerText = number;
19    ul.appendChild(li);
20  });

This might be more code than you were expecting. The first part should be simple to you now, we read the data from LocalStorage, increase each number by one with a map and then save the new array back to LocalStorage.

Then we have to update the UI by removing all the existing numbers and adding all the new ones.

If this feels clunky to you then you'd be right!

Making complicated UI's in JavaScript becomes very unwieldy and that's why user interfaces of any great complexity are made with a JavaScript frameworks like React, Vue, Angular etc.

This is the second time I've mentioned this now and will become an increasing theme over the coming days. HTML + CSS + JavaScript combined are truly incredible and there is nothing you can't make. But for your own long term sanity you will want to pick up a UI framework after this, my job is to get you to the point where you feel confident in you JavaScript abilities but also knowing that you can do more with JavaScript + a framework.


Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co