I am trying to return temperature results for a city and it does not seem like my API call is working. I am not sure if the problem is with my API key or my code. Please advise how I can fix this. If I open my console and go to the network settings, the api call does not come up after I enter the city name in the web app and press enter.
App.js:
import React, { useState } from 'react';
import './App.css';
function App() {
const apiKey = 'API KEY'; //I inserted my API key here
const [weatherData, setWeatherData] = useState([{}]);
const [city, setCity] = useState('');
const getWeather = (event) => {
if (event.key == 'ENter') {
fetch(
'https://api.openweathermap.org/data/2.5/weather?q=s{city}&units=imperil&APPID=${apiKey}' //this API I copied from the video tutorial
)
.then((response) => response.json())
.then((data) => {
setWeatherData(data);
setCity('');
});
}
};
return (
<div className="container">
<input
className="input"
placeholder="Enter City..."
onChange={(e) => setCity(e.target.value)}
value={city}
onKeyPress={getWeather}
/>
{typeof weatherData.main === 'undefined' ? (
<div>
<p>
{' '}
Welcome to weather app! Enter the city you want the weather of.
</p>
</div>
) : (
<div>
<p>{weatherData.name}</p>
<p>{Math.round(weatherData.main.temp)}℉</p>
<p>{weatherData.weather[0].main}</p>
</div>
)}
</div>
);
}
export default App;
App.css:
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding: 25px;
}
.input {
padding: 15px;
width: 80%;
margin: auto;
border: 1px solid lightgrey;
border-radius: 6px;
font-size: 16px;
}
.input:focus{
outline: none;
}
CodePudding user response:
There's a typo in your code
It should be
if (event.key == 'Enter')
in the getWeather
function