I am working on a search engine product and need to know the client country code.
I tried to get it with this URL and it returns server side country code.
How can I get the correct user country code when using getInitialProps
?
You can do it like this:
import React from 'react';
import fetch from 'isomorphic-unfetch';
// Vercel has created a data-fetching library called SWR (client side).
import useSWR from 'swr';
const API_URL = 'https://extreme-ip-lookup.com/json/';
async function fetcher(url) {
const res = await fetch(url);
const json = await res.json();
return json;
}
function Index() {
const { data, error } = useSWR(API_URL, fetcher);
if (error) return <div>failed to load</div>;
if (!data) return <div>loading...</div>;
const { countryCode } = data;
return (
<div>
<p>Country Code: {countryCode}</p>
</div>
);
}
export default Index;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With