Skip to content

Commit 43dbb2e

Browse files
authored
fix: ResizeObserver throws limit (#169)
1 parent 83e237c commit 43dbb2e

File tree

2 files changed

+17
-10
lines changed

2 files changed

+17
-10
lines changed

src/hooks/useHeights.tsx

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import * as React from 'react';
2-
import { useRef } from 'react';
2+
import { useRef, useEffect } from 'react';
33
import findDOMNode from 'rc-util/lib/Dom/findDOMNode';
4+
import raf from 'rc-util/lib/raf';
45
import type { GetKey } from '../interface';
56
import CacheMap from '../utils/CacheMap';
67

@@ -12,16 +13,16 @@ export default function useHeights<T>(
1213
const [updatedMark, setUpdatedMark] = React.useState(0);
1314
const instanceRef = useRef(new Map<React.Key, HTMLElement>());
1415
const heightsRef = useRef(new CacheMap());
15-
const heightUpdateIdRef = useRef(0);
16+
const collectRafRef = useRef<number>();
1617

17-
function collectHeight() {
18-
heightUpdateIdRef.current += 1;
19-
const currentId = heightUpdateIdRef.current;
18+
function cancelRaf() {
19+
raf.cancel(collectRafRef.current);
20+
}
2021

21-
Promise.resolve().then(() => {
22-
// Only collect when it's latest call
23-
if (currentId !== heightUpdateIdRef.current) return;
22+
function collectHeight() {
23+
cancelRaf();
2424

25+
collectRafRef.current = raf(() => {
2526
instanceRef.current.forEach((element, key) => {
2627
if (element && element.offsetParent) {
2728
const htmlElement = findDOMNode<HTMLElement>(element);
@@ -33,7 +34,7 @@ export default function useHeights<T>(
3334
});
3435

3536
// Always trigger update mark to tell parent that should re-calculate heights when resized
36-
setUpdatedMark(c => c + 1);
37+
setUpdatedMark((c) => c + 1);
3738
});
3839
}
3940

@@ -58,5 +59,9 @@ export default function useHeights<T>(
5859
}
5960
}
6061

62+
useEffect(() => {
63+
return cancelRaf;
64+
}, []);
65+
6166
return [setInstanceRef, collectHeight, heightsRef.current, updatedMark];
6267
}

tests/list.test.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,9 @@ describe('List.Basic', () => {
202202

203203
// Wait for collection
204204
await act(async () => {
205-
await Promise.resolve();
205+
await new Promise((resolve) => {
206+
setTimeout(resolve, 10);
207+
});
206208
});
207209

208210
wrapper.find('Filler').find('ResizeObserver').props().onResize({ offsetHeight: 100 });

0 commit comments

Comments
 (0)