"use client" import "react-international-phone/style.css" import { useController, useFormContext, useWatch } from "react-hook-form" import { useCallback, useEffect, useRef } from "react" import { defaultCountries, getCountry } from "react-international-phone" import ErrorMessage from "@/components/TempDesignSystem/Form/ErrorMessage" import { PhoneInput, type PhoneInputRefType } from "react-international-phone" import styles from "./phone.module.css" import type { PhoneProps } from "./phone" export default function Phone({ name = "phone", placeholder = "", registerOptions = { required: true, }, }: PhoneProps) { const phoneRef = useRef(null) const { control, formState } = useFormContext() const countryValue = useWatch({ name: "country" }) const defaultCountry = getCountry({ countries: defaultCountries, field: "name", value: countryValue, }) /** * Holds the previous selected country to be able to update * countrycode based on country select field. * Since PhoneInput inputs the countrys dialcode (country code) upon * selection, we need to check if the current value is just * the previously selected countrys dialcode number. */ const prevSelectedCountry = useRef(countryValue) const { field } = useController({ control, name, rules: registerOptions, }) const handleCountrySelectForPhone = useCallback( (country: string) => { const selectedCountry = getCountry({ countries: defaultCountries, field: "name", value: country, }) if (selectedCountry) { phoneRef.current?.setCountry(selectedCountry.iso2) prevSelectedCountry.current = country } }, [phoneRef.current, prevSelectedCountry.current] ) useEffect(() => { if (countryValue) { if (field.value) { if (prevSelectedCountry.current) { if (prevSelectedCountry.current !== countryValue) { const selectedCountryPrev = getCountry({ countries: defaultCountries, field: "name", value: prevSelectedCountry.current, }) if ( field.value.replace("+", "") === selectedCountryPrev?.dialCode ) { handleCountrySelectForPhone(countryValue) } } } else { handleCountrySelectForPhone(countryValue) } } else { handleCountrySelectForPhone(countryValue) } } }, [countryValue, prevSelectedCountry.current]) return (
) }