简体   繁体   中英

TypeError: Cannot read properties of undefined (reading 'country')

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);
        });
    }
  };
}

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.

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM