Home > OS >  pushing new object to array - cant get push() to work - using LocalStorage
pushing new object to array - cant get push() to work - using LocalStorage

Time:11-02

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"}

CodePudding user response:

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.

CodePudding user response:

At each method invocation, you are initializing existingItems object then storing its value with one item being the products hence the stored object will only hold one item at a time.

You should retrieve the compareItems stored value being your existingItems then append the new products objet to it:

const handleChange = () => {
   localStorage.setItem("item", JSON.stringify(products));
   const compareItems = JSON.parse(localStorage.getItem("compareItems"));
   var existingItems: any[] = compareItems ? compareItems : [];
   existingItems.push({ products });
   localStorage.setItem("compareItems", JSON.stringify(existingItems));
};
  • Related