Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Not working properly with MUI and asynchronous calls #175

Open
Loschcode opened this issue Apr 15, 2024 · 1 comment
Open

Not working properly with MUI and asynchronous calls #175

Loschcode opened this issue Apr 15, 2024 · 1 comment

Comments

@Loschcode
Copy link

Loschcode commented Apr 15, 2024

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
Copy link
Owner

goveo commented Apr 20, 2024

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...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants