AOS
AOS

Reputation: 89

Local Storage only displays the last value saved - JS

I have this list where I add list items and render them in the page Even though I can see local storage is indeed storing the items in an array, when I refresh the page it only displays the last value.

I created another function for render() which is exactly the same apart from the name render2() and it works fine... What I'm missing here??

The render() function should work when I invoke it at the top of the page but only render2() works..


  <form action="">
     <input type="text" name="item">
  </form>
  <ul class="list">
     <li>um</li>
  </ul>
   

``
const form = document.querySelector("form")
const list = document.querySelector(".list")
const items = JSON.parse(localStorage.getItem("items")) || []
console.log({
  items
})
//render()
render2();

form.addEventListener("submit", addItem)

function addItem(e) {
  e.preventDefault()
  const item = this.querySelector("[name=item]").value
  items.push(item)
  render()
  localStorage.setItem("items", JSON.stringify(items))
  this.reset()
}

function render() {
  let newItem;
  items.forEach(el => {
    newItem = document.createElement("li")
    newItem.innerText = el
  })
  list.appendChild(newItem)
}

function render2() {
  items.forEach(el => {
    newItem = document.createElement("li")
    newItem.innerText = el
    list.appendChild(newItem)
  })
}

Upvotes: 1

Views: 449

Answers (1)

Sever van Snugg
Sever van Snugg

Reputation: 713

The appendChild in the render is outside the loop only adding the last item to the DOM.

That's the difference at least.

Upvotes: 1

Related Questions