34 lines
1.1 KiB
TypeScript
34 lines
1.1 KiB
TypeScript
import { Country } from "@/components/PhoneInput/types";
|
|
import getFormat from "@/components/PhoneInput/utils/getFormat";
|
|
import countryOptionsDataMap from "@/components/PhoneInput/utils/countryOptionsDataMap";
|
|
import { CountryCode, parsePhoneNumberFromString } from "libphonenumber-js";
|
|
|
|
type InitialDataFromValue = {
|
|
country: Country;
|
|
format: ReturnType<typeof getFormat>;
|
|
localValue: string;
|
|
};
|
|
|
|
const getInitialDataFromValue = (
|
|
value: string | undefined,
|
|
initialCountryCode: string
|
|
): InitialDataFromValue => {
|
|
const defaultValue = {
|
|
country: countryOptionsDataMap[initialCountryCode],
|
|
format: getFormat(initialCountryCode as CountryCode),
|
|
localValue: "",
|
|
};
|
|
if (!value) return defaultValue;
|
|
const phoneNumber = parsePhoneNumberFromString(value);
|
|
if (!phoneNumber) return defaultValue;
|
|
if (!phoneNumber.country) return defaultValue;
|
|
|
|
return {
|
|
country: countryOptionsDataMap[phoneNumber.country],
|
|
localValue: phoneNumber.formatNational(),
|
|
format: getFormat(phoneNumber.country),
|
|
};
|
|
}
|
|
|
|
export default getInitialDataFromValue;
|