skip to Main Content

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?

2

Answers


  1. 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
    
    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search