Skip to content

Commit 80bcd6e

Browse files
authored
fix: Don't pass uninitialized ref to dispatchCommand, add warnings (#8327)
## Summary This PR adds warnings shown when the `scrollTo` or the `dispatchCommand` function is called with an uninitialized ref. It also early returns from the `dispatchCommand` function when the ref is uninitialized (has `null` value) and doesn't pass it to the native `dispatchCommand` method call. I added this PR as I feel that the #8245 issue is caused by the invalid use of the animated ref.
1 parent 675514b commit 80bcd6e

File tree

2 files changed

+25
-6
lines changed

2 files changed

+25
-6
lines changed

packages/react-native-reanimated/src/platformFunctions/dispatchCommand.ts

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,21 @@ function dispatchCommandNative(
3838
return;
3939
}
4040

41-
const shadowNodeWrapper = animatedRef() as ShadowNodeWrapper;
42-
global._dispatchCommand!(shadowNodeWrapper, commandName, args);
41+
const shadowNodeWrapper = animatedRef();
42+
43+
// This prevents crashes if ref has not been set yet
44+
if (!shadowNodeWrapper) {
45+
logger.warn(
46+
`Tried to dispatch command "${commandName}" with an uninitialized ref. Make sure to pass the animated ref to the component before using it.`
47+
);
48+
return;
49+
}
50+
51+
global._dispatchCommand!(
52+
shadowNodeWrapper as ShadowNodeWrapper,
53+
commandName,
54+
args
55+
);
4356
}
4457

4558
function dispatchCommandJest() {

packages/react-native-reanimated/src/platformFunctions/scrollTo.web.ts

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import type { ComponentRef } from 'react';
33
import type { ScrollView } from 'react-native';
44

5+
import { logger } from '../common';
56
import type { InternalHostInstance } from '../commonTypes';
67
import type { AnimatedRef } from '../hook/commonTypes';
78

@@ -14,9 +15,14 @@ export function scrollTo<TRef extends InternalHostInstance>(
1415
const element = animatedRef();
1516

1617
// This prevents crashes if ref has not been set yet
17-
if (element) {
18-
// By ScrollView we mean any scrollable component
19-
const scrollView = element as unknown as ComponentRef<typeof ScrollView>;
20-
scrollView?.scrollTo({ x, y, animated });
18+
if (!element) {
19+
logger.warn(
20+
'Called scrollTo() with an uninitialized ref. Make sure to pass the animated ref to the scrollable component before calling scrollTo().'
21+
);
22+
return;
2123
}
24+
25+
// By ScrollView we mean any scrollable component
26+
const scrollView = element as unknown as ComponentRef<typeof ScrollView>;
27+
scrollView?.scrollTo({ x, y, animated });
2228
}

0 commit comments

Comments
 (0)