Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot access updated state or props inside onPanResponderMove

What am I Trying to do: To change the state in response to user's up/down swipe. Environment: React native 0.61.5

I have the component as follows.

import React, { useRef, useState } from 'react';
import { View, PanResponder } from 'react-native';

function SimpleWrapper(props) {
  const { children } = props;

  const [abc, setabc] = useState(0);

  console.log('SimpleWrapper', abc);

  const panResponder = useRef(
    PanResponder.create({
      onStartShouldSetPanResponder: (evt, gestureState) => handleShouldSetPanResponder(evt, gestureState),
      // onStartShouldSetPanResponderCapture: (evt, gestureState) => handleShouldSetPanResponder(evt, gestureState),
      onMoveShouldSetPanResponder: (evt, gestureState) => handleShouldSetPanResponder(evt, gestureState),
      // onMoveShouldSetPanResponderCapture: (evt, gestureState) => handleShouldSetPanResponder(evt, gestureState),
      // onPanResponderGrant: (evt, gestureState) => console.log('onPanResponderGrant', gestureState),
      onPanResponderMove: (evt, gestureState) => handleonPanResponderMove(evt, gestureState),
      onPanResponderTerminationRequest: () => {}
      // onPanResponderRelease: (evt, gestureState) => handlePanResponderRelease(evt, gestureState)
    })
  ).current;

  const handleShouldSetPanResponder = (evt, gestureState) => {
    const { dy } = gestureState;
    const isvalid = evt.nativeEvent.touches.length === 1 && Math.abs(dy) > gestureConfig.gestureIsClickThreshold;
    return isvalid;
  };

  const handleonPanResponderMove = (evt, gestureState) => {
    const { dy, vy } = gestureState;
    console.log('in handleonPanResponderMove:', abc, gestureState);
    if (dy < 0) {
      setabc(abc + 1);
    } else if (dy > 0) {
      setabc(abc - 1);
    }
    // }
  };

  return (
    <View {...panResponder.panHandlers} style={}>
      {children}
    </View>
  );
}

export default SimpleWrapper;

Basically i want to increment/decrement the state parameter inside onMoveShouldSetPanResponder,

Now, On First fire of onMoveShouldSetPanResponder, 'abc' is incremented/decremented successfully. The topmost console in the component also shows new value.

However, After that in all consecutive fires, the console inside the onMoveShouldSetPanResponder function always prints abc as 0 (i.e. the initial value). It never changes.

Is it that we cannot access updated state inside onMoveShouldSetPanResponder? Am i missing something or is there another way to do this?

like image 728
varun Avatar asked Oct 11 '25 20:10

varun


1 Answers

The abc variable is a stale closure you can pass a callback to a state setter: setabc(currentValue=>currentValue + 1);

like image 141
HMR Avatar answered Oct 14 '25 12:10

HMR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!