nanadjei2
5 months ago

Append object to localStorage.

Posted 5 months ago by nanadjei2

Think of what I want to do like a shopping cart. I want to setItem new_order with value of an object like; {'item_one': orange, 'item_two': Mango, 'item_three': apple}; So I have written a function to check if new_order does not exist in storage then it should create it and set the 1st value. But if it exists, then it should update it.

This is the method to store items;

 storeInLocalStorage(item, keyAndvalue) {
      if (localStorage.getItem(item) == null) {
       localStorage.setItem(item, JSON.stringify(keyAndvalue));
       return;
    }

    var oldData = JSON.parse(localStorage.getItem(item)) || [];
   oldData.push(keyAndvalue);
   return;
}

Calling of the method:

     storeInLocalStorage("new_order", { yetAnother: "keyAnditsvalue" });
     storeInLocalStorage("new_order", { value1: "value2" });

But am getting it says push.function is undefined.

Please sign in or create an account to participate in this conversation.