baptiste
baptiste

Reputation: 100

Why when i add a new product in my local storage, he is replace by the new one

I don't understand in my code why when I click on my productBtn, my item in the local storage is replaced by the new one

buttonProduct = document.getElementById('productBtn');
  buttonProduct.addEventListener('click', () => {
    const storageCameras = localStorage.getItem('basketCameras') ? JSON.parse(localStorage.getItem('basketCameras')) : [];
    storageCameras.push(product._id)
    localStorage.setItem('basketCameras', JSON.stringify([product._id]));
  })
}

because in my code, I get an element, then I push, and finally, I set

is it because every time I click on productBtn I refresh my []?

I just want to add and display all my elements ( i got 5 items)

Upvotes: 0

Views: 45

Answers (1)

Nonik
Nonik

Reputation: 655

You should use storageCameras variable

buttonProduct = document.getElementById('productBtn');

  buttonProduct.addEventListener('click', () => {
    const storageCameras = localStorage.getItem('basketCameras') ? JSON.parse(localStorage.getItem('basketCameras')) : [];
    storageCameras.push(product._id)
    localStorage.setItem('basketCameras', JSON.stringify(storageCameras));
  })
}

Upvotes: 3

Related Questions