Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setState when withRepeat isFinished

I'm trying to setState inside withRepeat callback to show the button when the animations isFinished but the app closes. How can I update the state based on animation end?

  const [showBtn, setShowBtn] = React.useState(false);
  
  // ...

  React.useEffect(() => {
    circle.value = withRepeat(
      withSequence(
        withTiming(1, {
          duration: 4000,
        }),
        withTiming(1, {
          duration: 2000,
        }),
        withTiming(0, {
          duration: 4000,
        })
      ),
      2,
      false,
      (isFinished) => {
        setShowBtn(true); // <- app closes
      }
    );
  }, [showBtn]);

  return (
    {showBtn && (
      <Button onPress={() => {
        circle.value = 0;
        setShowBtn(false);
      }}>Restart</Button>
    )}
  )
like image 892
jessmzn Avatar asked Jan 23 '26 08:01

jessmzn


1 Answers

I found the answer, I did tried this before but didn't work, so I took another look at the reanimated 2 docs about runOnJs

Instead of using seState inside runOnJs, I created a function and then called runOnJs(updateShowBtn)();

Updated code:

const updateShowBtn = () => {
  setShowBtn(true);
};

...

(isFinished) => {
  if (isFinished) {
    runOnJS(updateShowBtn)();
  }
}
like image 179
jessmzn Avatar answered Jan 27 '26 02:01

jessmzn