feat: get country code from ip geolocation (#6880)

* feat: get coutnry code from ip geolocation

Signed-off-by: Udit Takkar <udit.07814802719@cse.mait.ac.in>

* fix: create new api route for fetching code

Signed-off-by: Udit Takkar <udit.07814802719@cse.mait.ac.in>

* chore: replace city with country

Signed-off-by: Udit Takkar <udit.07814802719@cse.mait.ac.in>

* refactor: create hook for country

Signed-off-by: Udit Takkar <udit.07814802719@cse.mait.ac.in>

---------

Signed-off-by: Udit Takkar <udit.07814802719@cse.mait.ac.in>
pull/7431/head
Udit Takkar 2023-02-26 00:45:05 +05:30 committed by zomars
parent 658ccc6517
commit 7b47956a34
2 changed files with 40 additions and 0 deletions

View File

@ -0,0 +1,20 @@
import type { NextRequest } from "next/server";
export const config = {
runtime: "experimental-edge",
};
export default async function handler(req: NextRequest) {
const countryCode = req.headers.get("x-vercel-ip-country") ?? "";
return new Response(
JSON.stringify({
countryCode,
}),
{
status: 200,
headers: {
"content-type": "application/json",
},
}
);
}

View File

@ -1,3 +1,5 @@
import { isSupportedCountry } from "libphonenumber-js";
import { useEffect, useState } from "react";
import type { Props } from "react-phone-number-input/react-hook-form";
import BasePhoneInput from "react-phone-number-input/react-hook-form";
import "react-phone-number-input/style.css";
@ -19,10 +21,12 @@ function PhoneInput<FormValues>({
onChange,
...rest
}: PhoneInputProps<FormValues>) {
const defaultCountry = useDefaultCountry();
return (
<BasePhoneInput
{...rest}
international
defaultCountry={defaultCountry}
name={name}
control={control}
onChange={onChange}
@ -35,4 +39,20 @@ function PhoneInput<FormValues>({
);
}
const useDefaultCountry = () => {
const [defaultCountry, setDefaultCountry] = useState("US");
useEffect(() => {
fetch("/api/countrycode")
.then((res) => res.json())
.then((res) => {
if (isSupportedCountry(res.countryCode)) setDefaultCountry(res.countryCode);
})
.catch((err) => {
console.log(err);
});
}, []);
return defaultCountry;
};
export default PhoneInput;