Data fetching from API issue

56 Views Asked by At

I am at beginner level of React framework and am creating a weather app. So I fetch the data from the API and pass the object as a value to a parameter in my component. Now when trying to access the inner data values of the object, I am facing an error.

So I took the parameter as in App.js

{weather && <WeatherDisp data = {weather}/>}

in WeatherDisp.js

const WeatherDisp = ({data}) => {
    return (
        <div>
            <p>{data.main.temp}</p>
        </div>
    );
}

on writing this I am getting the error as :

Cannot read properties of undefined (reading 'temp')

Can anyone help?

3

There are 3 best solutions below

0
krishn kumar modanval On

It would be great if you used loading while waiting for the API data response, and then rendered your component. Additionally, you can include checks to see if the data exists in the object or not. Please try the code below, as it should be helpful.

data && data.main && data.main.temp

or better way as below

data?.main?.temp
0
sahilatahar On

You can wait and show loading when data fetched then show it.

// App.jsx
import { useEffect, useState } from 'react'

function App() {
  
  const API_KEY = "YOUR_API_KEY";
  const [data, setData] = useState({});
  const [loading, setLoading] = useState(false);
  
  useEffect(() => {
    setLoading(true);
    (async () => {
      let response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=india&appid=${API_KEY}`).then((respond) => respond.json());

      setData(response);
      setLoading(false);
    })();
  }, []);

  return (
    <h1>{loading ? "Please wait!" : data?.main?.temp}</h1>
  )
}

export default App
0
salm00n On

It might be because your data that is being passed on is undefined. You can add a conditional check to verify if weather exists before rendering the WeatherDisp component. Here is an example:

App.js

{weather && Object.keys(weather).length > 0 && <WeatherDisp data={weather} />}

WeatherDisp.js

const WeatherDisp = ({ data }) => {
  return (
    <div>
      <p>{data && data.main && data.main.temp}</p>
    </div>
  );
};