1

I have an Angular application that has CRUD functionalities using localStorage. I need to gather a data object called rubberboot from a few input fields and push it to a localStorage key rubbberboots which holds an array of objects.

Stackblitz here: https://stackblitz.com/edit/github-4lgqkx

Using the input fields from lisaa.component.ts the data should be

{ name: "foo", color: "bar", price: 123, availability: 123 }

but instead an empty array is being pushed to localStorage

[[]]

This piece of code in kumpparit.service.ts pushes the rubberboot to the localStorage:

addRubberboot = (rubberboot: rubberboot) => {
    if (typeof (Storage) != undefined) {
      let rubberboots = JSON.parse(localStorage.getItem("rubberboots"));
      rubberboot.id = this.generateId();

      rubberboots.push(rubberboot);
      localStorage.setItem("rubberboots", JSON.stringify(rubberboots));
    }
  }

and this function generates an id for the rubberboot object, since the id comes from localStorage instead of the input fields:

generateId = () => {
    if (typeof (Storage) != undefined) {
      let rubberboots: rubberboot[] = JSON.parse(localStorage.getItem("rubberboots"));
      let index = 0;
      for (let rubberboot of rubberboots) {
        index++;
      }
      return index;
    }
  }

I am expecting the localStorage key rubberboot to now hold the value of

[ { name: "foo", color: "bar", price: 123, availability: 123, id: 0 } ]

and the next push operation to localStorage would set the value of the rubberboot key to

[ 
    { name: "foo", color: "bar", price: 123, availability: 123, id: 0 },
    { name: "foo", color: "bar", price: 123, availability: 123, id: 1 } 
]
aleksejjj
  • 1,405
  • 2
  • 18
  • 28

1 Answers1

4

The problem is you define ruberboot as an array and assign it an array in your LisaaComponent and not an object in your component. The serialization then tries to serialize an array of array.

Change it to this (I added some initializers, you could change the definition to allow undefined values for the properties if you want).

rubberboot: rubberboot = {availability: 0, color: '', name: '', price: 0, id: 0};

Originally you had:

rubberboot: rubberboot[] = [];

Your updated stackblitz

Igor
  • 60,821
  • 10
  • 100
  • 175