3

I have been reading the documentation reanimated 2 Hooks and searched all the internet for the better explained blog or any code but couldn't find any one , Can anyone please explain and give example with source code .As example

const App = () => {
  const [state, setState] = useState(0);
  const sv = useSharedValue(0);

  const handler = useAnimatedGestureHandler(
    {
      onEnd: (_) => {
        sv.value = state;
      },
    },
    dependencies
  );
  //...
  return <></>;
};

But when i tried as

const [test, setTest ] = useState(true);

const gestureHandler = useAnimatedGestureHandler({
        onStart : (event,context)=>{
            console.log("onstart");
            setTest(true);
            context.startX = X.value;
        },
        onActive : (event,context)=>{
            console.log("onactive");   
            X.value = context.startX + event.translationX;
        },
        onEnd : (event,context)=>{
            console.log("onEnd");
            setTest(false);
        }
        
    },
    [test]
    )

i got error as

Tried to Synchronously call function (bound dispatchAction)
 from different thread.
skyboyer
  • 22,209
  • 7
  • 57
  • 64
Muhammad Mehdi
  • 531
  • 1
  • 5
  • 14

1 Answers1

4

You need to use runOnJS since you're not calling a worklet, so try with:

const gestureHandler = useAnimatedGestureHandler(
  {
    onStart: (event, context) => {
      console.log('onstart');
      runOnJS(setTest)(true);
      context.startX = X.value;
    },
    onActive: (event, context) => {
      console.log('onactive');
      X.value = context.startX + event.translationX;
    },
    onEnd: (event, context) => {
      console.log('onEnd');
      runOnJS(setTest)(false);
    },
  },
  // [test], you don't need dependencies in this case
);

You need to use dependencies when you want to update a value, used by a worklet, on re-render. In your first example you assign state to a shared value on gesture end. In order to use the updated state on re-render you need to put it in the hook dependencies, otherwise the worklet will capture and use the first value only: 0 in this case.

Omar
  • 16,329
  • 10
  • 48
  • 66