How to perform client side data fetching in Next.js
Asked Answered
B

1

8

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?

Bridal answered 20/2, 2020 at 15:29 Comment(2)
Tried calling that API from the app when a component mounts?Trueblood
Thanks, Drew for contact me. I tried it on the server site from getInitialProps function.Bridal
Q
12

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;
Quillet answered 20/2, 2020 at 15:40 Comment(5)
I tried it already, but I am getting the server country code and not the client country code.Bridal
Think about this! When you deploy on some server, it will return the deployed server country code and not the client country.Bridal
When the page is loaded in the browser SWR will fetch the data.Quillet
Ah, I am sorry. I was missing the edition of your answer. Let me check it again.Bridal
Worth noting that NextJS implicitly imports React in jsx files and polyfills fetch on server & client so no need to import them, at least in recent versions.Hurff

© 2022 - 2024 — McMap. All rights reserved.