Skip to content

Commit 6e335ae

Browse files
authored
Fix useListData remove method for all selection (#2206)
* Fix useListData remove method for all selection * Handle empty items scenario for remove method
1 parent d516424 commit 6e335ae

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

packages/@react-stately/data/src/useListData.ts

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -211,9 +211,15 @@ export function createListActions<T>(opts: ListOptions<T>, dispatch: (updater: (
211211
let keySet = new Set(keys);
212212
let items = state.items.filter(item => !keySet.has(getKey(item)));
213213

214-
let selection = new Set(state.selectedKeys);
215-
for (let key of keys) {
216-
selection.delete(key);
214+
let selection: Selection = 'all';
215+
if (state.selectedKeys !== 'all') {
216+
selection = new Set(state.selectedKeys);
217+
for (let key of keys) {
218+
selection.delete(key);
219+
}
220+
}
221+
if (selection === 'all' && items.length === 0) {
222+
selection = new Set();
217223
}
218224

219225
return {

packages/@react-stately/data/test/useListData.test.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,28 @@ describe('useListData', function () {
225225
expect(result.current.selectedKeys).toEqual(new Set(['Julia']));
226226
});
227227

228+
it('should preserve all selected value through a remove call', function () {
229+
let {result} = renderHook(() => useListData({initialItems: initial, getKey, initialSelectedKeys: 'all'}));
230+
231+
act(() => {
232+
result.current.remove('Sam');
233+
});
234+
235+
expect(result.current.selectedKeys).toEqual('all');
236+
});
237+
238+
it('should change all selection to empty set if last item is removed', function () {
239+
let {result} = renderHook(() => useListData({initialItems: initial, getKey, initialSelectedKeys: 'all'}));
240+
241+
act(() => {
242+
result.current.remove('Sam');
243+
result.current.remove('David');
244+
result.current.remove('Julia');
245+
});
246+
247+
expect(result.current.selectedKeys).toEqual(new Set());
248+
});
249+
228250
it('should remove multiple items', function () {
229251
let {result} = renderHook(() => useListData({initialItems: initial, getKey, initialSelectedKeys: ['Sam', 'David', 'Julia']}));
230252
let initialResult = result.current;

0 commit comments

Comments
 (0)