-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Description
🐛 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) {
...
}
react-spectrum/packages/@react-stately/data/src/useTreeData.ts
Lines 136 to 149 in d978363
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 |