Skip to content

Commit

Permalink
fix: Add getCountryCode function to retrieve the country code from a …
Browse files Browse the repository at this point in the history
…phone number
  • Loading branch information
iPagar committed Feb 21, 2024
1 parent e6461bf commit 22ee5ed
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
12 changes: 11 additions & 1 deletion src/use-phone-state/use-phone-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,14 @@ export const phoneValidationSchema = (
}
}, invalid);

export function getCountryCode(phone: string) {
const parsedNumber = parsePhoneNumberFromString(phone);
if (!parsedNumber) {
return '';
}
return parsedNumber.country;
}

export function formatPhoneNumber(phoneNumber: string, country?: string) {
const parsedNumber = parsePhoneNumberFromString(phoneNumber);
if (!parsedNumber) {
Expand Down Expand Up @@ -55,7 +63,9 @@ export const usePhoneState = ({
initialCountry = 'US',
initialPhoneNumber = '',
} = {}) => {
const [country, setCountry] = useState(initialCountry);
const [country, setCountry] = useState(
getCountryCode(initialPhoneNumber) || initialCountry
);
const [phoneNumber, setPhoneNumber] = useState(
formatPhoneNumber(initialPhoneNumber, initialCountry)
);
Expand Down
4 changes: 3 additions & 1 deletion stories/phone-input.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -554,7 +554,9 @@ export function BasicWithCountryFlag() {
</ul>
</PhoneInput.Dialog>
)}
<PhoneInput.NumberInput placeholder="Phone" />
{({ phone }) => (
<PhoneInput.NumberInput placeholder="Phone" value={phone} />
)}
</PhoneInput.Root>
);
}
Expand Down

0 comments on commit 22ee5ed

Please sign in to comment.