Nbot07
Nbot07

Reputation: 13

Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'length')

Why is children.length resulting in Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'length') especially since the value of children.length is successfully displayed on the console?

const getParentId = (childId) => {
    var queue = [ds]
    while(queue.length > 0){
      const children = queue[0].children
      queue.push(children)
      console.log("children.length = "+children.length)
      for (let i = 0; i < children.length; i++){
        if (children[i].id === childId) {return queue[0].id}
      }
      queue.shift()
    }
  }

  const addSiblingNodes = async () => {


    const child = [...selectedNodes][0]
    const childId = child.id
    const newNodes = getNewNodes()

    await dsDigger.addSiblings(childId, newNodes);
    setDS({ ...dsDigger.ds });
    
    console.log("the parent of "+childId +" is "+ getParentId(childId))
  };

Upvotes: 1

Views: 12621

Answers (1)

traktor
traktor

Reputation: 19301

The while loop continues to loop after an entry in queue has no children property - the code actually pushes undefined onto queue. When it goes to report the length of undefined on the next line it throws the error causing the promise rejection.

Correct me if I'm wrong, but wouldn't it be true to say that no children array has a children property because only child nodes have children properties? If this is indeed true, the error is occuring on the second iteration of the while loop.

I suggest reviewing the design of getParentId because it seems to be attempting a branch walk of eldest children starting from the ds node - and possibly should be conducting a tree walk of all child branches.

Upvotes: 1

Related Questions