Skip to content

Commit

Permalink
Add support for nested filtering in useListData
Browse files Browse the repository at this point in the history
  • Loading branch information
gijsroge committed Mar 29, 2024
1 parent 784737e commit 7f99ecc
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
19 changes: 17 additions & 2 deletions packages/@react-stately/data/src/useListData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,9 +152,24 @@ export function useListData<T>(options: ListOptions<T>): ListData<T> {
filterText: initialFilterText
});

const filterItems = (items: T[], filterText: string): T[] => {
return items.reduce((acc: T[], item: any) => {
if (item.children) {
const children = filterItems(item.children, filterText);
if (children.length > 0) {
acc.push({...item, children});
}
} else if (filter(item, filterText)) {
acc.push(item);
}
return acc;
}, []);
};

let filteredItems = useMemo(
() => filter ? state.items.filter(item => filter(item, state.filterText)) : state.items,
[state.items, state.filterText, filter]);
() => (filter ? filterItems(state.items, state.filterText) : state.items),
[state.items, state.filterText, filter]
);

return {
...state,
Expand Down
24 changes: 24 additions & 0 deletions packages/@react-stately/data/test/useListData.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,23 @@ const many = [
{name: 'Eleven'}
];

const grouped = [
{
name: 'One', children: [
{name: 'One - Child 1'},
{name: 'One - Child 2'}
]
},
{name: 'Two'},
{
name: 'Three',
children: [
{name: 'Three - Child 1'}
]
}
];


let getKey = (item) => item.name;
let filter = (item, text) => item.name.includes(text);

Expand Down Expand Up @@ -801,4 +818,11 @@ describe('useListData', function () {
expect(result.current.items).toHaveLength(1);
expect(result.current.items[0]).toEqual({name: 'David'});
});

it('should support filtering nested items', function () {
let {result} = renderHook(() => useListData({initialItems: grouped, getKey, filter, initialFilterText: 'Three - Child 1'}));

expect(result.current.items).toHaveLength(1);
expect(result.current.items[0]).toEqual(grouped[2]);
});
});

0 comments on commit 7f99ecc

Please sign in to comment.