Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pushing new object to array – cant get push() to work – using LocalStorage

I’ve tried a few stack examples. an i am still just rewriting what i was hoping to be adding to … mainly we have a list of check box items each time you check it i would like existing items to turn into a list of those object so we can use them on a ‘comparing’ page

const handleChange = () => {
   localStorage.setItem("item", JSON.stringify(products)); <-- works as expected
   var existingItems: any[] = [];
   existingItems?.push({ products });
   localStorage.setItem("compareItems", JSON.stringify(existingItems));
};

existingItems is always = to products i want existing items to = [{item}, {item},] and so on

detail of what products would be:
products (object of key and values frm api) = {name: "Product 1", description: "Product 1", isActiveForEntry: true, displayRank: 0, sku: "ABC123"}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have to get the existing items first before defaulting to an empty array:

const existingItems: any[] = JSON.parse(localStorage.getItem("compareItems")) ?? [];
//                                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
existingItems.push({ products });

localStorage.setItem("compareItems", JSON.stringify(existingItems));

See nullish coalescing operator for what the ?? means.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading