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

222
Visualizações
Uncaught TypeError: Cannot read properties of undefined (reading 'name') - ReactJS
import Info from "./components/Info";
import Search from "./components/Search";
import axios from "axios";
import { useEffect, useState } from "react";

const App = () => {

  const API_KEY = `<REDACTED>`
  const baseURL = `http://api.weatherapi.com/v1/current.json?key=${API_KEY}&q=`

  const [weatherData, setWeatherData] = useState({})
  const [search, setSearch] = useState('London')
  const [error, setError] = useState('')

  useEffect(() => {
    axios.get(`${baseURL + search}`)
      .then(resp => {
        setWeatherData(resp.data)
      })
      .catch(error => setError(error.message))
  }, [search])

  console.log(weatherData.location.name);

  return (
    <div className="App">
      <h1 style={{ textAlign: 'center', marginBottom: '2rem' }}>{error}</h1>
      <Search setSearch={setSearch} />
      <div className="container">
        <Info weatherData={weatherData} />
      </div>
    </div>
  );
}

export default App;

I'm trying to create a weather app in react. I'm using the weather API that you can see in the code (maybe you should take a look at the API structure also). When I console log weatherData.location I get the normal weather data. But when I try weatherData.location.name I get the error that says: Uncaught TypeError: Cannot read properties of undefined (reading 'name'). I've started learning React two weeks ago so I'm still a beginner... Thank you.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

This occurs when the API has not sent a response yet and weather data is still empty. I'd recommend adding a [loading,setLoading] state and setting that to true by default. Then set that to false in the .then(resp => function. Make an if statement to check if loading is false, and if so then print/render the contents of weatherData.

about 4 years ago · Juan Pablo Isaza Relatório

0

You need to add ternery operator in the console.log

like console.log(weatherData? location ? .name ) or You can try console.log(weatherData && weatherData.location && weatherDataname.location.name)

its happening becaus in initial state it cant read the value of name because probabaly its an empty string .

try this method .

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