garganurag893 / react-native-phone-number-input

React Native component for phone number.
MIT License
373 stars 216 forks source link

Warnings when component is unmounted due to conditional rendering #125

Open gt-adam opened 1 year ago

gt-adam commented 1 year ago

Hi,

We are experiencing the following issues with our current setup when the component is unmounted (due to a conditional state variable) in our Expo app:

const phoneInput = useRef(null); const [phoneRecipientInputValue, setPhoneRecipientInputValue] = useState(''); const [formattedPhoneRecipientInputValue, setFormattedPhoneRecipientInputValue] = useState(''); const [isSendingMessage, setisSendingMessage] = useState(false); const [messageType, setMessageType] = useState(() => { return props.replyData?.replyMessageType; });

{(messageType == 1 || messageType == 7) && <> <PhoneInput ref={phoneInput} defaultCode='GB' placeholder='Enter phone number here' value={phoneRecipientInputValue} onChangeText={setPhoneRecipientInputValue} onChangeFormattedText={setFormattedPhoneRecipientInputValue} containerStyle={{ flex: 0.9, borderRadius: 25, borderColor: '#5e6874', borderWidth: 1, alignSelf: "flex-start" }} textContainerStyle={{ backgroundColor: "#FFFFFF", paddingHorizontal: 0, paddingVertical: 0, marginRight: 15 }} flagButtonStyle={{ alignSelf: "center" }} disabled={isSendingMessage} textInputStyle={{ fontSize: 14 }} codeTextStyle={{ fontSize: 14 }}> </PhoneInput> } We get the following error messages:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in %s.%s, the componentWillUnmount method, in PhoneInput

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in %s.%s, a useEffect cleanup function, in CountryPicker

Does anyone have any suggestions on how to resolve this?

PopJoestar commented 1 year ago

For country-picker look at this PR https://github.com/xcarpentier/react-native-country-picker-modal/pull/379. For PhoneInput, I fixed it with a little hack:

constructor(props) {
    super(props);
    this.unmounted = false //add this
    this.state = {
      code: props.defaultCode ? undefined : "91",
      number: props.value
        ? props.value
        : props.defaultValue
        ? props.defaultValue
        : "",
      modalVisible: false,
      countryCode: props.defaultCode ? props.defaultCode : "IN",
      disabled: props.disabled || false,
    };
  }

async componentDidMount() {
    const { defaultCode } = this.props;
    if (defaultCode) {
      const code = await getCallingCode(defaultCode);
      if (this.unmounted == true) {return} // add this
      this.setState({ code });
    }
  }
// add this
 componentWillUnmount() {
    this.unmounted = true
  }