Search code examples
jsonstringify

Error: Converting circular structure to JSON


I have a problem with my application. Anyone can help me?

Error: Converting circular structure to JSON

My Service to create items and save on localstorage:

  addItem(item: Item): void {
    this.itens.unshift(item);
    let itens;
    if (localStorage.getItem('itens') == null){
      itens = [];
      itens.unshift(itens);
      localStorage.setItem('itens', JSON.stringify(itens));
    } else {
      JSON.parse(localStorage.getItem('itens'));
      itens.unshift(itens);
      localStorage.setItem('itens', JSON.stringify(itens));
    }
  }

And my component.ts:

  addItem(): void  {
    this.itemAdicionado.emit({
      nome: this.nome,
      unidade: this.unidade,
      quantidade: this.quantidade,
      preco: this.preco,
      perecivel: true,
      validade: this.validade,
      fabricacao: this.fabricacao,
    });

    this.nome = '';
    this.unidade ;
    this.quantidade ;
    this.preco;
    this.validade;
    this.fabricacao;

    console.log(this.nome, this.unidade, this.quantidade, this.preco, this.validade, this.fabricacao);
  }

Solution

  • This isn't an Angular error. It's a JavaScript runtime error thrown by the JSON.stringify function. The error tells you that itens contains a circular object reference. This is OK while you run the application, but when stringifying it causes a problem: the JSON generated would become infinitely long.

    As Kevin Koelzer indicated in his answer. The problem is that you wrote itens.unshift(itens);. Basically this adds the array of items to the array of items, thus creating a circular reference. Therefore, writing itens.unshift(item); instead solves your problem and is probably what you intended to do anyway.