javascript - TypeError: Cannot read properties of undefined (reading 'country') - Stack Overflow

admin2025-04-19  0

I'm trying to fetch data from an API and use that data in my app. But the problem is that when I try to get a certain object or data from the JSON I've just got from the API, I get a TypeError: Cannot read property 'country' of undefined. The property DOES exist. By the way, I'm using React.js. I really appreciate your help & guidance. Here is the code:

App.js

{typeof weather != 'undefined' ? (
  <div>
    <div className="location-box">
      <div className="location">
        
        {weather.name},{weather.sys.country} 
      </div>
      <div className="date"> {dateBuilder(new Date())} </div>
    </div>

    <div className="weather-box">
      <div className="weather-temperature">15*C</div>
      <div className="weather">Sunny </div>
    </div>
  </div>
) : ("NULL")}

Api from where we are going to fetched the data.

function App() {
  const [query, setQuery] = useState("");
  const [weather, setWeather] = useState({});

  const Search = (evt) => {
    if (evt.key === "Entre") {
      debugger;
      fetch(`${api.base}weather?q=${query}&units=metric&APPID${api.key}`)
        .then((res) => res.json())

        .then((result) => {
          setWeather(result);
          setQuery("");
          console.log(result);
        });
    }
  };
}

I'm trying to fetch data from an API and use that data in my app. But the problem is that when I try to get a certain object or data from the JSON I've just got from the API, I get a TypeError: Cannot read property 'country' of undefined. The property DOES exist. By the way, I'm using React.js. I really appreciate your help & guidance. Here is the code:

App.js

{typeof weather != 'undefined' ? (
  <div>
    <div className="location-box">
      <div className="location">
        
        {weather.name},{weather.sys.country} 
      </div>
      <div className="date"> {dateBuilder(new Date())} </div>
    </div>

    <div className="weather-box">
      <div className="weather-temperature">15*C</div>
      <div className="weather">Sunny </div>
    </div>
  </div>
) : ("NULL")}

Api from where we are going to fetched the data.

function App() {
  const [query, setQuery] = useState("");
  const [weather, setWeather] = useState({});

  const Search = (evt) => {
    if (evt.key === "Entre") {
      debugger;
      fetch(`${api.base}weather?q=${query}&units=metric&APPID${api.key}`)
        .then((res) => res.json())

        .then((result) => {
          setWeather(result);
          setQuery("");
          console.log(result);
        });
    }
  };
}
Share edited Dec 6, 2021 at 7:53 Ayman El Temsahi 2,6102 gold badges19 silver badges29 bronze badges asked Dec 6, 2021 at 7:35 Ihtisham KhattakIhtisham Khattak 1801 gold badge2 silver badges11 bronze badges 4
  • That property doesn't exist because when the ponent is initially rendered you have no data. You have an empty object. It probably is in the data, but you need to check for that once the data is loaded and the state is updated. – Andy Commented Dec 6, 2021 at 7:37
  • Could you console.log the weather variable and see if weather.sys actually exists? – LoKat Commented Dec 6, 2021 at 7:38
  • Okay i will check the weather in console – Ihtisham Khattak Commented Dec 6, 2021 at 7:40
  • Put this: {weather.name},{weather.sys?.country} – davood Sandoghsaz Commented Dec 6, 2021 at 7:52
Add a ment  | 

2 Answers 2

Reset to default 2

If you are certain that the property does exist, then it must be the initial render. You initialise the useStaet with {} but guard against undefined. So change useState({}) to useState().

const [weather, setWeather] = useState();

You can also add a null check when you read country.

{weather.name}, {weather.sys?.country}

The problem is because of your weather check: typeof weather != 'undefined' while your init value of weather is {}. In order to solve the problem don't set init value for weather. like this:

const [weather, setWeather] = useState();

So, in the first render weather value will be undefined and in the next render it contains your api response.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745071762a283324.html

最新回复(0)