Skip to content

Commit b9e85f0

Browse files
authored
fix: Prevent use-table-interaction-metrics from calling debounced function after unmounting (#4073)
1 parent fe52d2c commit b9e85f0

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/internal/hooks/use-table-interaction-metrics/__tests__/use-table-interaction-metrics.test.tsx

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,5 +273,22 @@ describe('useTableInteractionMetrics', () => {
273273
})
274274
);
275275
});
276+
277+
test('componentUpdated should not be called after unmount', () => {
278+
const { setLastUserAction, rerender, unmount } = renderUseTableInteractionMetricsHook({});
279+
280+
setLastUserAction('filter');
281+
rerender({ loading: true });
282+
rerender({ loading: false });
283+
284+
// Unmount before the debounced callback fires
285+
unmount();
286+
287+
// Run timers to trigger the debounced callback
288+
jest.runAllTimers();
289+
290+
// componentUpdated should not have been called because component was unmounted
291+
expect(ComponentMetrics.componentUpdated).toHaveBeenCalledTimes(0);
292+
});
276293
});
277294
});

src/internal/hooks/use-table-interaction-metrics/index.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,10 +49,18 @@ export function useTableInteractionMetrics<T>({
4949
const lastUserAction = useRef<{ name: string; time: number } | null>(null);
5050
const capturedUserAction = useRef<string | null>(null);
5151
const loadingStartTime = useRef<number | null>(null);
52+
const isMountedRef = useRef(true);
5253

5354
const metadata = useRef({ itemCount, getComponentIdentifier, getComponentConfiguration, interactionMetadata });
5455
metadata.current = { itemCount, getComponentIdentifier, getComponentConfiguration, interactionMetadata };
5556

57+
useEffect(() => {
58+
isMountedRef.current = true;
59+
return () => {
60+
isMountedRef.current = false;
61+
};
62+
}, []);
63+
5664
useEffect(() => {
5765
if (isInFunnel) {
5866
return;
@@ -94,6 +102,9 @@ export function useTableInteractionMetrics<T>({
94102
}, [instanceIdentifier, loading, taskInteractionId, isInFunnel]);
95103

96104
const debouncedUpdated = useDebounceCallback(() => {
105+
if (!isMountedRef.current) {
106+
return;
107+
}
97108
ComponentMetrics.componentUpdated({
98109
taskInteractionId,
99110
componentName: 'table',

0 commit comments

Comments
 (0)