简体   繁体   中英

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.

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.

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 .

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