Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

262
Visualizações
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);
        });
    }
  };
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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}
about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda