goveo / react-international-phone

☎️ International phone input component for React
https://react-international-phone.vercel.app/
MIT License
295 stars 54 forks source link

Not working properly with MUI and asynchronous calls #175

Open Loschcode opened 7 months ago

Loschcode commented 7 months ago

I'm using GraphQL and will receive some phone asynchronously. Long story short, the example in your documentation is not working properly because it doesn't take into consideration asynchronous data coming in.

const [phone, setPhone] = useState<string>("")

// Some asynchronous calls that will setPhone()

return (<PhoneInput
  value={phone}
  label="Phone"
  onChange={(phone) => {
    setPhone(phone);
  }}
/>)

The problem is that in your implementation you don't make any difference between onChange from the client and onChange from your own system adding the country code (e.g. +1) so in my case I'm having my API response being overwritten by an additional +1 for no reason.

The only workaround I found was to detect onFocus and activate onChange once the user actually goes on that phone input.

const [byFocus, setByFocus] = useState<boolean>(false);
const { inputValue, handlePhoneValueChange, inputRef, country, setCountry } =

usePhoneInput({
    defaultCountry,
    value,
    countries: defaultCountries,
    onChange: (data) => {
      if (byFocus) {
        onChange(data.phone);
      }
    },
});

<TextField
  variant="outlined"
  label="Phone number"
  color="primary"
  placeholder="Phone number"
  value={inputValue}
  onChange={handlePhoneValueChange}
  onFocus={() => setByFocus(true)}
  ...
/>

This is an abstract of my solution, it's not perfect. A better solution would be to avoid firing onChange when initializing the country code, or at least have another type of event for that.

goveo commented 7 months ago

Hey @Loschcode! Are you sure that the phone value that you are setting asynchronously starts with +? Can you also share a piece of logic where you are setting a new phone value to the phone input, please? 🙏

If you change value prop everything should work fine...