如何在 Next.js 中执行客户端数据获取

Jam*_*Lin 4 client location reactjs next.js

我正在开发搜索引擎产品,需要知道客户端国家/地区代码。

我尝试使用此 URL获取它并返回服务器端国家/地区代码。

使用时如何获取正确的用户国家代码getInitialProps

ElD*_*n90 8

你可以这样做:

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;
Run Code Online (Sandbox Code Playgroud)