Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: useTreeData add replaceAll #7821

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions packages/@react-stately/data/docs/useListData.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,9 @@ list.move('Snake', 0);
```tsx
list.update('Snake', {name: 'Rattle Snake'});
```

### Replacing the tree

```
list.replaceAll([{name: 'Fox', children: [{name: 'Rabbit'}]}])
```
10 changes: 9 additions & 1 deletion packages/@react-stately/data/src/useTreeData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,12 @@ export interface TreeData<T extends object> {
* @param key - The key of the item to retrieve.
*/
getItem(key: Key): TreeNode<T> | undefined,


/**
* Replace the whole tree.
* @param newItems - The new items to replace the tree with.
*/
setRootItems(newItems: T[]): void,
/**
* Inserts an item into a parent node as a child.
* @param parentKey - The key of the parent item to insert into. `null` for the root.
Expand Down Expand Up @@ -257,6 +262,9 @@ export function useTreeData<T extends object>(options: TreeOptions<T>): TreeData
getItem(key: Key) {
return nodeMap.get(key);
},
setRootItems(newItems: T[]) {
setItems(buildTree(newItems, new Map()));
},
insert(parentKey: Key | null, index: number, ...values: T[]) {
setItems(({items, nodeMap: originalMap}) => {
let {items: newNodes, nodeMap: newMap} = buildTree(values, originalMap, parentKey);
Expand Down
15 changes: 15 additions & 0 deletions packages/@react-stately/data/test/useTreeData.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -745,4 +745,19 @@ describe('useTreeData', function () {
expect(result.current.items[1].key).toEqual('Emily');
expect(result.current.items.length).toEqual(2);
});

it('Should replace the tree with new nodes', function () {
const initialItems = [...initial, {name: 'Emily'}, {name: 'Eli'}];
let {result} = renderHook(() =>
useTreeData({initialItems, getChildren, getKey})
);
act(() => {
result.current.replaceAll([{name: 'Robert', children: [{name: 'Linh'}]}, {name: 'Stanley'}]);
});
expect(result.current.items[0].key).toEqual('Robert');

expect(result.current.items[0].children[0].key).toEqual('Linh');
expect(result.current.items[1].key).toEqual('Stanley');
expect(result.current.items.length).toEqual(2);
});
});