Skip to content

Commit

Permalink
fix: loadData not keep fresh (#599)
Browse files Browse the repository at this point in the history
* test: test driven

* fix: cache of loading

* fix: off topic

* fix: sync load logic

* chore: fix lint
  • Loading branch information
zombieJ authored Nov 21, 2024
1 parent 48076ee commit 35d98f5
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/OptionList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -241,13 +241,15 @@ const OptionList: React.ForwardRefRenderFunction<ReviseRefOptionListProps> = (_,
onKeyUp: () => {},
}));

const loadDataFun = useMemo(
() => (searchValue ? null : (loadData as any)),
const hasLoadDataFn = useMemo(
() => (searchValue ? false : true),
[searchValue, treeExpandedKeys || expandedKeys],
([preSearchValue], [nextSearchValue, nextExcludeSearchExpandedKeys]) =>
preSearchValue !== nextSearchValue && !!(nextSearchValue || nextExcludeSearchExpandedKeys),
);

const syncLoadData = hasLoadDataFn ? loadData : null;

// ========================== Render ==========================
if (memoTreeData.length === 0) {
return (
Expand Down Expand Up @@ -289,7 +291,7 @@ const OptionList: React.ForwardRefRenderFunction<ReviseRefOptionListProps> = (_,
showIcon={showTreeIcon}
switcherIcon={switcherIcon}
showLine={treeLine}
loadData={loadDataFun}
loadData={syncLoadData}
motion={treeMotion}
activeKey={activeKey}
// We handle keys by out instead tree self
Expand Down
46 changes: 46 additions & 0 deletions tests/Select.loadData.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/* eslint-disable no-undef, react/no-multi-comp, no-console */
import React from 'react';
import { render, fireEvent, act } from '@testing-library/react';

import TreeSelect from '../src';

describe('TreeSelect.loadData', () => {
it('keep sync', async () => {
const Demo = () => {
const [treeData, setTreeData] = React.useState([
{
title: '0',
value: 0,
isLeaf: false,
},
]);

const loadData = async () => {
const nextId = treeData.length;

setTreeData([
...treeData,
{
title: `${nextId}`,
value: nextId,
isLeaf: false,
},
]);
};

return <TreeSelect open treeData={treeData} loadData={loadData} />;
};

render(<Demo />);

for (let i = 0; i < 5; i += 1) {
fireEvent.click(document.querySelector('.rc-tree-select-tree-switcher_close'));
await act(async () => {
await Promise.resolve();
});
expect(
document.querySelectorAll('.rc-tree-select-tree-list .rc-tree-select-tree-treenode'),
).toHaveLength(2 + i);
}
});
});

0 comments on commit 35d98f5

Please sign in to comment.