Skip to content

useTreeData runtime error: Cannot read properties of undefined when reading map. #2548

@reidbarber

Description

@reidbarber

🐛 Bug Report

Discussed in #2546

Originally posted by kyosimba November 11, 2021
I tried to run the example https://react-spectrum.adobe.com/react-stately/useTreeData.html#example . It seems that when mapping over initialItems I get cannot read properties of undefined. I am using @react-stately/data ^3.4.2 what am I missing.

let  tree = useTreeData({
    initialItems: [
      {
        name: "People",
        items: [{ name: "David" }, { name: "Sam" }, { name: "Jane" }],
      },
      {
        name: "Animals",
        items: [{ name: "Aardvark" }, { name: "Kangaroo" }, { name: "Snake" }],
      },
    ],
    initialSelectedKeys: ["Sam", "Kangaroo"],
    getKey: (item) => item.name,
    getChildren: (item) => item.items,
  });

🤔 Expected Behavior

The user should be able to use:

getChildren: (item) => item.items

😯 Current Behavior

The example found at https://react-spectrum.adobe.com/react-stately/useTreeData.html#example is not working.

The user must handle the case of no children via:

getChildren: (item) => item.items || []

💁 Possible Solution

Add an empty array as a default parameter to buildTree in useTreeData.ts.

 function buildTree(initialItems: T[] = [], parentKey?: Key | null) {
    ...
  }

function buildTree(initialItems: T[], parentKey?: Key | null) {
return initialItems.map(item => {
let node: TreeNode<T> = {
key: getKey(item),
parentKey: parentKey,
value: item,
children: null
};
node.children = buildTree(getChildren(item), node.key);
map.set(node.key, node);
return node;
});
}

🔦 Context

💻 Code Sample

https://codesandbox.io/s/usetreedata-undefined-children-y5pxp?file=/src/App.js

🌍 Your Environment

Software Version(s)
react-spectrum
Browser
Operating System

🧢 Your Company/Team

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions