Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform client side data fetching in Next.js

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?

like image 653
James Lin Avatar asked Jan 25 '23 07:01

James Lin


1 Answers

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;
like image 170
ddon-90 Avatar answered Jan 31 '23 08:01

ddon-90