简体   繁体   中英

React-Phone-Number-Input + React-Hook-Form: How to get current country code in controller validation?

I'm using react-phone-number-input library. The phone number input is not required but if the number is present I wish it could be validated before the form is sent.

If the cellphone field is pristine / left untouched when form is submitted then isValid accepts undefined (valid state).

If country code is changed right away (without actually inputting the number) isValid accepts the selected country's calling code (eg +46 for Sweden). This is still a perfectly valid case.

When accessed in the isValid function the phoneCountryCode always holds the previous selected value. So there's always a disparity between the validated phone number and the current country code. I'm not sure if the problem is library-specific, maybe it's my mistake. How do I get rid of the mentioned disparity?

I made a reproduction on CodeSandbox .

import PhoneInput, {
  parsePhoneNumber,
  getCountryCallingCode
} from "react-phone-number-input";

const [phoneCountryCode, phoneCountryCodeSetter] = useState('DE');

<Controller 
  name="cellphone"
  rules={{
    validate: {
      isValid: value => {
        if(value) {
          const callingCode = getCountryCallingCode(phoneCountryCode); 
          if(! new RegExp(`^\\+${callingCode}$`).test(value)) {
            // The parsePhoneNumber utility returns null 
            // if provided with only the calling code
            return !!parsePhoneNumber(value);
          }
        }
        return true;
      }
    }
  }}
  control={control}
  render={({ field }) => (
    <PhoneInput 
      {...field}
      onCountryChange={(v) => phoneCountryCodeSetter(v)}
      limitMaxLength={true}
      international={true}
      defaultCountry="DE"
    />
  )}
/>

It's a react specific, nothing wrongs in the library. React never update state immediately, state updates in react are asynchronous; when an update is requested there's no guarantee that the updates will be made immediately. Then updater functions enqueue changes to the component state, but react may delay the changes.

for example:

const [age, setAge] = useSate(21);
const handleClick = () => {
    setAge(24)
    console.log("Age:", age);
}

You'll see 21 logged in the console .

So this is how react works. In your case, as you change country this "onCountryChange" event triggers updating function to update the state and to validate the phone number but the state is not updated yet that's why it is picking the previous countryCode value(Do console log here).

To understand this more clearly put this code inside your component.

useEffect(() => {
    console.log("useEffect: phoneCountryCode", phoneCountryCode);
  }, [phoneCountryCode]);


console.log(phoneCountryCode, value); // inside isValid()

useEffect callback will be called when phoneCountryCode value is updated and console.log inside isValid() will be called before the state gets updated.

Hopes this makes sense. Happy Coding!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM