I work with the lottie-web package in a .web.js file under React Native (Expo).
My problem is that the let variable anim is undefined in the functions in useImperativeHandle. In the useEffect anim works wonderfully. For example if I access anim.play() right after the initialize at useEffect it works. But at the play() function in imperative it doesn't work.
At my parent component I create a ref with useRef and pass the ref to the component
const lottieAnim = useRef(null);
--
let anim;
useEffect(() => {
const lottieOptions = {
container: divContainer.current,
renderer: 'svg',
loop,
autoplay,
segments: segments !== false,
animationData,
rendererSettings,
};
anim = lottie.loadAnimation({ ...lottieOptions, ...options });
// anim.play(); works here
if (onAnimationFinish) {
anim.addEventListener('complete', onAnimationFinish);
}
}, []);
useImperativeHandle(ref, () => ({
stop() {
anim.stop();
},
pause() {
anim.pause();
},
play() {
anim.play();
// anim is undefined
},
setSpeed(s) {
anim.setSpeed(s);
},
setDirection(d) {
anim.setDirection(d);
},
playSegments(s) {
anim.playSegments(s);
},
}));