如何在 Next.js 应用程序中调用外部 API?

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

我正在设计一个天气应用程序作为简历项目。我正在尝试调用 WeatherAPI 以获取其

currentdata.json
调用提供的当前天气数据。我实际上如何在代码中做到这一点?

我有一个页面:

// /src/app/page.js
import Card from "@/lib/components/card";
import { fetchCurrentData } from "@/lib/data";

export default async function Page() {
  //fetching data...
  const currentWeather = await fetchCurrentData();

  //hardcoded card data for testing
  const currWeatherCardData = {
    top: 'Saturday, June 1st, 2024',
    main: '31\u00b0C',
    bottom: 'Sunny'
  };
  //more card data constants for other cards, same top/main/bottom...

  return (
    <main className="flex flex-col m-24 gap-8">
      <Card data={currWeatherCardData}/> 
      <Card data={highLowsCardData}/>
      <Card data={precipCardData}/>
      <Card data={uviCardData}/>
    </main>
  );
}

我正在尝试让

fetchCurrentData()
调用 API。

// src/lib/data.ts
export async function fetchCurrentData() {
  try {
    const currentData = await fetch('https://api.weatherapi.com/v1/current.json?q=LOCATION&key=APIKEY');
    console.log(currentData.json())
    return currentData;
  } catch (error) {
    console.error('API Error: ', error);
    throw new Error('Failed to fetch current weather data.');
  }
}

fetchCurrentData()
正在返回一个
Response
对象,我不太确定如何解析并将其获取到
page.js
具体来说,例如,我不确定如何将
localtime
从JSON获取到
Cards
之一作为文本。

供参考,API GET 请求返回一个 JSON 对象,如下所示:

{
  "location": {
    "name": "New York",
    "region": "New York",
    "country": "United States of America",
    "lat": 40.71,
    "lon": -74.01,
    "tz_id": "America/New_York",
    "localtime_epoch": 1717386775,
    "localtime": "2024-06-02 23:52"
  },
  "current": {
    "last_updated_epoch": 1717386300,
    "last_updated": "2024-06-02 23:45",
    "temp_c": 22.8,
    "temp_f": 73,
    "is_day": 0,
    "condition": {
      "text": "Partly cloudy",
      "icon": "//cdn.weatherapi.com/weather/64x64/night/116.png",
      "code": 1003
    },
    "wind_mph": 3.8,
    "wind_kph": 6.1,
    "wind_degree": 200,
    "wind_dir": "SSW",
    "pressure_mb": 1014,
    "pressure_in": 29.93,
    "precip_mm": 0,
    "precip_in": 0,
    "humidity": 59,
    "cloud": 75,
    "feelslike_c": 24.8,
    "feelslike_f": 76.6,
    "windchill_c": 22.8,
    "windchill_f": 73,
    "heatindex_c": 24.8,
    "heatindex_f": 76.6,
    "dewpoint_c": 13.9,
    "dewpoint_f": 57,
    "vis_km": 16,
    "vis_miles": 9,
    "uv": 1,
    "gust_mph": 6.3,
    "gust_kph": 10.2
  }
}

我的方法是最佳实践吗?或者有更好的方法吗?

任何帮助将非常感激!

javascript reactjs next.js weather-api
1个回答
0
投票

直接在组件中使用API调用 如果您更喜欢直接在组件中进行 API 调用(例如,响应用户操作),您可以使用 fetch 或 axios:

// pages/index.js
   import { useEffect, useState } from 'react';
    function HomePage() {
  const [data, setData] = useState(null);

  useEffect(() => {
    async function fetchData() {
      const res = await fetch('https://api.example.com/data');
      const currentWeather = await res.json();
      setData(currentWeather);
    }
    
    fetchData();
  }, []);

  if (!data) return <div>Loading...</div>;

  return (
    <div>
      <h1>Data from API</h1>
      {/* Use data as per need */}
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

export default HomePage;
© www.soinside.com 2019 - 2024. All rights reserved.