1

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))
  };
Nbot07
  • 13
  • 1
  • 1
  • 4

1 Answers1

1

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.

traktor
  • 17,588
  • 4
  • 32
  • 53
  • 1
    Thank you so much for your answer! The real issue was in the question you posed. `queue.push(children)` should be something like `children.forEach(child => queue.push(child))` In English, I was setting the next queue item to a list instead of actual nodes. Also, my design of getParentId seems to be equivalent to this answer https://stackoverflow.com/a/1616365/17011629 – Nbot07 Sep 27 '21 at 05:53