Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(android,animated-sensor): Fix HMR for Animated Sensor #5646

Merged
merged 4 commits into from
Feb 12, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 31 additions & 12 deletions src/reanimated2/hook/useAnimatedSensor.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
'use strict';
import { useEffect, useRef } from 'react';
import { useEffect, useMemo, useRef } from 'react';
import { initializeSensor, registerSensor, unregisterSensor } from '../core';
import type {
SensorConfig,
Expand Down Expand Up @@ -94,12 +94,28 @@ export function useAnimatedSensor(
sensorType: SensorType,
userConfig?: Partial<SensorConfig>
): AnimatedSensor<ValueRotation> | AnimatedSensor<Value3D> {
const config: SensorConfig = {
interval: 'auto',
adjustToInterfaceOrientation: true,
iosReferenceFrame: IOSReferenceFrame.Auto,
...userConfig,
};
const userConfigRef = useRef(userConfig);

const hasConfigChanged =
userConfigRef.current?.adjustToInterfaceOrientation !==
userConfig?.adjustToInterfaceOrientation ||
userConfigRef.current?.interval !== userConfig?.interval ||
userConfigRef.current?.iosReferenceFrame !== userConfig?.iosReferenceFrame;

if (hasConfigChanged) {
userConfigRef.current = { ...userConfig };
}

const config: SensorConfig = useMemo(
() => ({
interval: 'auto',
adjustToInterfaceOrientation: true,
iosReferenceFrame: IOSReferenceFrame.Auto,
...userConfigRef.current,
}),
[userConfigRef.current]
);

const ref = useRef<AnimatedSensor<Value3D | ValueRotation>>({
sensor: initializeSensor(sensorType, config),
unregister: () => {
Expand All @@ -110,11 +126,14 @@ export function useAnimatedSensor(
});

useEffect(() => {
const newConfig = {
...config,
...userConfig,
ref.current = {
sensor: initializeSensor(sensorType, config),
unregister: () => {
// NOOP
},
isAvailable: false,
config,
};
ref.current.sensor = initializeSensor(sensorType, newConfig);

const sensorData = ref.current.sensor;
const adjustToInterfaceOrientation =
Expand Down Expand Up @@ -148,7 +167,7 @@ export function useAnimatedSensor(
return () => {
ref.current.unregister();
};
}, [sensorType, userConfig]);
}, [sensorType, config]);

return ref.current as AnimatedSensor<ValueRotation> | AnimatedSensor<Value3D>;
}