0

I'm using React Native and Reanimated and I want an animation to play after 2 seconds. When a user moves a card, the card should stay at it's new position for 2 seconds, and then move back to it's place. This is what I have:

  const panGesture = useAnimatedGestureHandler<PanGestureHandlerGestureEvent>({
onActive: event => {
  translateX.value = event.translationX;
  if (event.translationX <= 0) {
    // disabling swiping from right to left
    translateX.value = 0;
  }
},
onEnd: event => {
  const shouldStick = translateX.value >= TRANSLATE_X_THRESHOULD;
  if (shouldStick) {
    translateX.value = withTiming(120);
    runOnJS(moveBack)(translateX);
  } else {
    translateX.value = withTiming(0);
  }
},
});

I tried using setTimeOut to count 2 seconds, and then update translateX but I get this error:

undefined is not an object (evaluating 'fun.__callAsync')

This is moveBack function:

const moveBack = (translateX: Animated.SharedValue<number>) => {
console.log("TRANSLATEX: " + translateX);

setTimeout(() => {
  translateX.value = 0;
}, 2000);
}

I don't even see the TRANSLATEX log, so I guess it won't even get there. I can't really figure out what's the problem or how to word it so I can find a solution.

John Doah
  • 1,839
  • 7
  • 25
  • 46

3 Answers3

1

when using runOnJS

const doSomething = () => { ... } // declare arrow function before runOnJS

runOnJS(doSomething)(arg)

function doSomething(){ ... } // can declare normal function before/after runOnJS coz of hoisting

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 17 '22 at 06:44
1

If you are declaring the function after you are calling runOnJS, then this error occurs. You need to declare that function before using runOnJS (above that line)

For example:

const functionToBeCalled = () => {...do your job here...}

// Then you can call this on runOnJs below: 

runOnJs(functionToBeCalled)()
Barry Michael Doyle
  • 9,333
  • 30
  • 83
  • 143
Adem Bacaj
  • 11
  • 2
0

The solution was way easier than I thought. I'm using Reanimated 2.2.0 and there is withDelay option to add to the animation and it works great.

This is what I added after translateX.value = withTiming(120); (instead of the runOnJs line):

translateX.value = withDelay(2000, withTiming(0));

So right after setting translateX to 120, it waits 2 seconds, and then setting the value back to 0.

John Doah
  • 1,839
  • 7
  • 25
  • 46