cannot update a component from inside the function body of a different component - React Native?

Viewed 5631

I have a child component "Text Input" and passes the value to as a prop like this

export default function MobileInput(props) {
  const [mobileNumber, setMobileNumber] = React.useState('');

  return (
    <View style={styles.inputBox}>
        <TextInput
          value={mobileNumber}
          onChangeText={(number) => setMobileNumber(number)}
          onEndEditing={props.saveMobileNumber(mobileNumber)} // here
        />
    </View>
  );
}

In Parent, I got the value from child

const [mobile, setMobile] = useState('');


const getMobile = (number) => {
    number ? setMobile(number) : null; // here's I got this warnning
    console.log('getMobile-number-from-child', number);
  };


const reSendMobile = () => { // other function I want to call passed on mobile number I got from child component 
    if (mobile?.length) {
      alert('Done');
      setReSend(false);
      setSeconds(10);
    } else {
      alert('Please write your number before press send!');
    }
  };


<MobileInput saveMobileNumber={getMobile} />

I see this issue But I'm already using React 16.13.1

4 Answers

TextInputs property onEndEditing accepts a function that is called when text input ends.. Instead of a function, you are passing the result of your props.saveMobileNumber function that is called when the component renders. Try passing a function that calls saveMobileNumber instead:

onEndEditing={() => props.saveMobileNumber(mobileNumber)}

Your code will be much easier to read/debug if you avoid keeping the same state in multiple components. You can pass mobile and setMobile to the child through props and avoid having to create separate state for the same data.

Try this:

<View style={styles.inputBox}>
        <TextInput
          value={mobileNumber}
          onChangeText={(number) => setMobileNumber(number)}
          onEndEditing={() => props.saveMobileNumber(mobileNumber)} // change here
        />
</View>

The event onEndEditing accepts a function call Just update to call a arrow function :

onEndEditing={() => props.saveMobileNumber(mobileNumber)}

For me, i was updating activity title outside the useEffect hook. When i moved the code

into useEffect hook, the error just gone.

Related