'Trying to fetch data from and external API but code breaks
I'm trying to fetch data from an external API. It shows at first but when I refreshes the browser, it goes blank. The code is in my GitHub repo. thanks
https://github.com/Rengkat/weather-app.git
Solution 1:[1]
The initial state of data is {}. As a consequence, data.name and data.sys are undefined, so trying to render data.sys.country throws an error before the app can render the input field.
<div className="details">
<div className="country">
<h3>
{data.name}, {data.sys.country}
</h3>
I recommend setting the initial state of data to null and wrapping everything other than the input field in a conditional that only allows rendering if data is truthy:
function FetchDataComponent() {
const [data, setData] = useState(null);
...
return (
<div className="container">
<div className="input">
<input
type="text"
placeholder="Enter country..."
value={country}
onChange={handleChange}
onKeyPress={fetchData}
/>
</div>
{data ? (
<div className="details">
<div className="country">
<h3>
{data.name}, {data.sys.country}
</h3>
</div>
...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jarmo |
