【发布时间】:2022-12-18 07:33:09
【问题描述】:
我正在尝试从 Foreca Weather api (https://rapidapi.com/foreca-ltd-foreca-ltd-default/api/foreca-weather/) 获取天气数据。 要获取当前天气,需要 location 参数,它是一串数字,因城市而异。这个位置参数可以从他们的位置搜索端点获取。
我有一个函数 searchCity,它获取位置 ID,然后将其传递给 weatherUrl 以获取当前天气。 第一次搜索城市时,我确实得到了位置数组,但不是当前天气,axios 会抛出 400 错误请求错误。 我第二次搜索时,它给了我两个,但当前的天气响应来自上次 api 调用。
Here's the code.
import React from 'react'
import { useState } from 'react';
import axios from 'axios';
const Home = () => {
// const [weather, setWeather] = useState({});
const [city, setCity] = useState('');
const [location, setLocation] = useState([""]);
const [weather, setWeather] = useState({});
const url = `https://foreca-weather.p.rapidapi.com/location/search/${city}`
let weatherUrl;
const options = {
headers: {
'X-RapidAPI-Key': 'apiKeyHere',
'X-RapidAPI-Host': 'foreca-weather.p.rapidapi.com'
}
};
const weatherOptions = {
params: { alt: '0', tempunit: 'C', windunit: 'MS', tz: 'Europe/London', lang: 'en' },
headers: {
'X-RapidAPI-Key': 'apiKeyHere',
'X-RapidAPI-Host': 'foreca-weather.p.rapidapi.com'
}
};
const searchCity = async (e) => {
try {
if (e.key === 'Enter') {
await axios.get(url, options).then((response) => {
setLocation(response.data.locations);
console.log(response.data);
weatherUrl = `https://foreca-weather.p.rapidapi.com/current/${location[0]?.id}`;
})
setCity('')
// To show the current weather of the city searched
currentWeather();
}
} catch (err) {
console.error(err);
}
}
const currentWeather = async () => {
try {
await axios.get(weatherUrl, weatherOptions).then((response) => {
setWeather(response.data);
console.log(response.data);
})
} catch (err) {
console.error(err);
}
}
return (
<> <div>
<div className="search">
<input
value={city}
onChange={e => setCity(e.target.value)}
onKeyPress={searchCity}
type="text" />
</div>
<div className="weather">
<h1>City:{location[0]?.name}</h1>
<h1>Country:{location[0]?.country}</h1>
<h1>id:{location[0]?.id}</h1>
<h1>weather:{weather.current?.temperature}</h1>
</div>
</div>
</>
)
}
export default Home;
What am I doing wrong or are there better ways to achieve this?
【问题讨论】:
标签: javascript reactjs rest axios fetch-api