Search code examples
reactjslocationclientnext.js

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?


Solution

  • 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;