1

I'm trying to find a replacement for ComponentWillMount method with useEffect. But panresponder variable is not created before the initial render. Can anyone please tell me if any mistakes I'm doing here? without useEffect, the page is getting rendered. gestures are not captured.

      const makeup = () => {
        useEffect(() => {
            console.log('I am about to render!');
            const panResponder = useRef(
              PanResponder.create({
                onStartShouldSetPanResponder: (e, gestureState) => true,
                onPanResponderMove: (e, gestureState) => {....},
                onPanResponderRelease: (e, gestaureState) => {....}
              }));
          },[]);

        return ARTICLES.map((item, i) => {
          console.log("Makeup i:"+i+" item:"+item);
          if (i === index.currentIndex - 1) {
            return (
              <Animated.View
                key={item.id}
                style={swipeCardPosition.getLayout()}
                {...panResponder.panHandlers}
              >
                  
              </Animated.View>
            );
          }
          if (i < index.currentIndex) {
            return null;
          }
          return (
            <Animated.View
              key={item.id}
              style={index.currentIndex === i ? position.getLayout() : null}
              {...(index.currentIndex === i
                ? { ...panResponder.panHandlers }
                : null)}
>
            </Animated.View>
          );
        }).reverse();
      };
[Error on execution][1] [1]: https://i.stack.imgur.com/sls5E.png
  • You're storing your panResponder inside a useRef, you should check for the property `current` on it and then spread it, right now `panResponder.panHandlers` does not even exist. It should be `panResponder.current.panHandlers` – Konstantin Feb 07 '21 at 14:09
  • Thank you for checking @Konstantin !. The below solution has worked. – Chandhirasekaran Feb 09 '21 at 14:32

1 Answers1

0

Check the official docs. It describes how to use PanResponder with functional components.

For example:

const ExampleComponent = () => {
  const panResponder = React.useRef(
    PanResponder.create({
      onStartShouldSetPanResponder: (e, gestureState) => true,
      onPanResponderMove: (e, gestureState) => {....},
      onPanResponderRelease: (e, gestaureState) => {....}
    })
  ).current;

  return <View {...panResponder.panHandlers} />;
};

Your example won't work, for a large number of reasons, most notably because you can't call useRef inside useEffect.

ivanmoskalev
  • 2,004
  • 1
  • 16
  • 25