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

问题描述 投票:0回答:1

感谢您访问我的问题。最近,我正在研究搜索引擎产品,需要了解客户的国家/地区代码。我尝试使用下面的URL来获取它,并返回服务器端国家代码。

https://extreme-ip-lookup.com/json/

请让我知道在getInitialProps时如何获取正确的用户国家/地区代码。

reactjs location client next.js
1个回答
1
投票

您可以这样操作:

import React from 'react';
import fetch from 'isomorphic-unfetch';
// ZEIT 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;
© www.soinside.com 2019 - 2024. All rights reserved.