I have this react component which every time it's rendered show the country information that receives via props (country) and using the weather stack API must show also the capital weather at the current time. The first part (displaying the country data that comes from the props) works fine but I'm struggling to get the data from the weather API. I see on console that I'm getting the current weather but can't assign it to weather variable using setState() therefore my app crashes.
This is the component code I have so far, I've tried using async/await and .then synataxis in case I was mispelling something but always I get the same result:
const CountryDetails = async ({country}) => {
const [weather, setWeather] = useState({});
// const hook = async () => {
// const result = await axios.get(`http://api.weatherstack.com/current?access_key=${WEATHER_API}&query=${country.capital}`);
// console.log(result.data);
// setWeather(result.data.current);
// console.log(weather);
// }
const hook = () => {
axios.get(`http://api.weatherstack.com/current?access_key=${WEATHER_API}&query=${country.capital}`).then((response) => {
console.log('then');
setWeather({
temperature: response.data.current.temperature,
img: response.data.current.weather_icons,
wind: response.data.current.wind_speed,
dir: response.data.current.wind_direction
});
console.log(response.data.current);
});
}
useEffect(hook, []);
console.log(weather);
return (
<>
<h1>{country.name}</h1>
<p>capital {country.capital}</p>
<p>population {country.population}</p>
<h2>languages</h2>
<ul>
{country.languages.map((lang) => {
<li key={lang.name}>{lang.name}</li>;
})}
</ul>
<img src={country.flag}></img>
<h2>Weather in {country.capital}</h2>
<p><b>temperature: </b>{weather.current.temperature}</p>
<img src={weather.current.weather_icons} />
<p><b>wind: </b>{weather.current.wind_speed} direction {weather.current.wind_direction}</p>
</>
);
};
sandbox with the whole code: https://codesandbox.io/s/vigilant-ride-h3t1j
asyncin your component's function definition? Would just removing it work?weatherwith an empty object and try to access its properties in your jsx. the line<p><b>temperature: </b>{weather.current.temperature}</p>will fail when your component is rendered