How to display the data from fetch request to the user browser in ReactJS

Hi everyone, I am building a weather forecast app in which I make a fetch request to get the data from the server throung some api. I get the data all right and can even log it to the console, but then if I try displying theb same data to the browser I get an error saying “reading undefined name ". it also loged twice on the console

below is the code I wrote


import React from 'react';
import { useState, useEffect } from 'react
const  WeatherApp = () => {
const [data, setData] = useState([])

useEffect(()=>{ fetch(['http://api.weatherstack.com/forecast?access_key=7464a7f86c4a82b9af9f31d8bb612c0f&query=Accr](http://api.weatherstack.com/forecast?access_key=7464a7f86c4a82b9af9f31d8bb612c0f&query=Accra)a') .then(res => res.json()) .then(data => { setData(data) console.log(data); });
}, []) 
return ( <div className="weatherAppContainer">
<form className='submitForm'>
<input type="text" />
<button type='submit'>search</button>
{ <h2>{data.location.name}</h2>
<p>Wind dir:{data.current.wind_dir}</p>
<p>Wind speed:{data.current.wind_speed}</p>
<p>humidity:{data.current.humidity}</p> }
</form>
</div> );}
export default WeatherApp;

Hi there!

You are missing the quote in the end after react.

Remove the [] and () brackets around URL. These characters were breaking the URL string.

Set data to null instead of an empty array to simplify checking if data exists.
Add .catch((error) => console.error('Error fetching data:', error)); to handle errors from the API request.

Use data && data.location && data.current to check if data has loaded before accessing its properties. This avoids errors when data is still null.
Move the <input /> and <button /> outside the conditionals for cleaner structure.

1 Like