2

I've started to play around with react-native-reanimated v2.

const fontSize = useSharedValue(25);
const config = {
    duration: 500,
    easing: Easing.bezier(0.5, 0.01, 0, 1),
};
const fontStyle = useAnimatedStyle(() => {
    return {
      fontSize: withTiming(fontSize.value, config, (isFinished) => {
        if (isFinished) {
          console.log('isFinished');
        }
      }),
    };
});

return (
  <Button
        title="toggle"
        onPress={() => {
          fontSize.value = 1;
        }}
      />
)

The above code block initially sets the font size to 25, and on press starts an animation where it gradually reduces it to 1.

When the animation is finished, I want to change the text.

However, the callback with isFinished is called instantly, before I press the button. The moment the app renders.

The code block is pretty much from their docs, so I'm unsure what I'm doing wrong.

Is it possible to make sure the callback is only called after the animation is finished? Not on render?

UPDATE

A hack I've put together is setting a state const [buttonPressed, setButtonPressed] = useState(false); and checking for this along with isFinished, and setting this to true when the button has been pressed.

But this is a horrible workaround.

victorbalssa
  • 2,762
  • 2
  • 13
  • 25
Jake Owen
  • 137
  • 1
  • 9

1 Answers1

0

Surprisingly, the callback function is called every frame!

However, the function is passed 2 parameters - finished and current. In order to execute your code iff the animation is finished, you have to check if the finished boolean is true.

Random example from my personal code:

didConfirmBackgroundSharedVal.value = withTiming(1, { duration: 1000 }, (finished) => {
  if (postSuccess && finished) runOnJS(postSuccess)()
})

As of writing this answer, the reanimated docs are wrong. They claim this for the withTiming API:

callback: A function called upon animation completion. If the animation is cancelled, the callback will receive false as the argument; otherwise, it will receive true.

victorbalssa
  • 2,762
  • 2
  • 13
  • 25