From 35d98f5356d48448b37b0a09d9ef3440b93a2acd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BA=8C=E8=B4=A7=E7=88=B1=E5=90=83=E7=99=BD=E8=90=9D?= =?UTF-8?q?=E5=8D=9C?= Date: Thu, 21 Nov 2024 22:13:50 +0800 Subject: [PATCH] fix: `loadData` not keep fresh (#599) * test: test driven * fix: cache of loading * fix: off topic * fix: sync load logic * chore: fix lint --- src/OptionList.tsx | 8 +++--- tests/Select.loadData.spec.tsx | 46 ++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 3 deletions(-) create mode 100644 tests/Select.loadData.spec.tsx diff --git a/src/OptionList.tsx b/src/OptionList.tsx index aaa9d0ee..bbfa37f9 100644 --- a/src/OptionList.tsx +++ b/src/OptionList.tsx @@ -241,13 +241,15 @@ const OptionList: React.ForwardRefRenderFunction = (_, 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 ( @@ -289,7 +291,7 @@ const OptionList: React.ForwardRefRenderFunction = (_, showIcon={showTreeIcon} switcherIcon={switcherIcon} showLine={treeLine} - loadData={loadDataFun} + loadData={syncLoadData} motion={treeMotion} activeKey={activeKey} // We handle keys by out instead tree self diff --git a/tests/Select.loadData.spec.tsx b/tests/Select.loadData.spec.tsx new file mode 100644 index 00000000..c938d95c --- /dev/null +++ b/tests/Select.loadData.spec.tsx @@ -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 ; + }; + + render(); + + 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); + } + }); +});