Search code examples
javascriptvue.jserror-handlingruntime-errorcallstack

VueJS, an endless loop of object creation and Error: "Maximum call stack size exceeded"


Last time I asked a similar but more complex question. Here I want to ask about one specific problem.

There is a function that accepts an object as input:

onFormSubmit (data) {
      const newObj = {
        ...data,
        id: Math.random()
      }
      if (!data.leader) {
        this.list.push(newObj)
        this.saveList()
      } else {
        for (let i = 0; i < this.list.length; i++) {
          if (this.list[i].id === data.leader) {
            this.list[i].children.push(newObj)
            this.saveList()
          }
        }
      }
    }

saveList () {
      const parsed = JSON.stringify(this.list)
      localStorage.setItem('list', parsed)
    }

Input:

{leader: 42, name: "Name", number: "12345", id: "", children: Array(0)}

Data structure:

data: () => ({
    list: [{
      leader: '',
      name: 'Silvia',
      number: +54321236576,
      id: 17,
      children: [{
        leader: 17,
        name: 'Joe',
        number: +87653459809,
        id: 191,
        children: []
      }]
    },
    {
      leader: '',
      name: 'Victor',
      number: +98765434560,
      id: 42,
      children: [{
        leader: 42,
        name: 'Sam',
        number: +145735643798,
        id: 202,
        children: [{
          leader: 202,
          name: 'Mona',
          number: +77774352309,
          id: 2092
        }]
      }]
    }]
  }),

The task of the function is to add this object to the array of objects, to the top level if !data.leader = true, or as a child element if !data.leader = false.

The new element is added correctly.

The new child element is added to the pre-written data correctly.

But when trying to add a child to the newly created element, an endless loop and an error occurs. The function starts endlessly creating a copy of the object.

What i'm doing wrong?


Solution

  • Okay, i solved it this way:

    onFormSubmit (data) {
          let newId = Math.floor(Math.random() * 100) + data.leader
          let newObj = {}
          newObj = {
            ...data,
            id: newId
          }
          if (!data.leader) {
            this.list.push(newObj)
            this.saveList()
          } else {
            for (let i = 0; i < this.list.length; i++) {
              if (this.list[i].id === newObj.leader) {
                this.list[i].children = [newObj]
                this.saveList()
              }
            }
          }
        },