Actualmente estoy tratando de crear un sitio web meteorológico usando weatherapi, pero tengo un problema. Si registro el objeto de ubicación, no hay error, pero si intento registrar algo más profundo que ese objeto, como el nombre de la ciudad, no puede leer las propiedades de indefinido. Si comento el registro cuando usa el nombre de la ciudad, luego lo elimino nuevamente y no vuelvo a cargar la página, entonces registrará el nombre de la ciudad sin error.
import React from 'react'; import './index.css'; import Navbar from "./components/Navbar" import {useState} from "react" import Weather from './components/Weather'; function App() { const [inputData, setInputData] = useState({}) const [currentWeather, setCurrentWeather] = useState([]) const [loc, setLoc] = useState({loc:"Arlington"}) let apiKey = "xxxxxxxx" // console.log("Location: "+ loc.loc) React.useEffect(() =>{///Finds weather data of certain location console.log(loc.loc) fetch(`https://api.weatherapi.com/v1/current.json?key=${apiKey}&q=${loc.loc}&aqi=no`) .then(res => { if(res.ok){ return res.json() } }) .then(data => { if(data !=null){//Only change currentWeather when there is data for it setCurrentWeather(data) }else{ alert(`${loc.loc} was not found`) } }) }, [loc]) React.useEffect(() =>{///Finds locations with search bar fetch(`https://api.weatherapi.com/v1/search.json?key=${apiKey}&q=${loc.loc}&aqi=no`) .then(res => res.json()) .then(data => { if(data.loc == null){ }else{ setLoc(data) } }) }, []) //console.log(currentWeather.location.name) return ( <div className="App"> <Navbar inputData={inputData} setLoc={setLoc} setInputData={setInputData}/> <Weather currentWeather={currentWeather}/> </div> ); } export default App;Algunos problemas que veo:
currentWeather en una matriz, pero probablemente debería ser undefined o un objeto ( {} ) en función de su uso. Para arreglar esto, use uno de estos: const [currentWeather, setCurrentWeather] = useState() // or const [currentWeather, setCurrentWeather] = useState({})currentWeather.location.name antes de haber actualizado currentWeather para tener esas propiedades. Por eso te da ese error.La mejor solución para esto es usar el encadenamiento opcional https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
Así que prueba esto:
console.log(currentWeather?.location?.name)console.log está solo en el cuerpo del componente de la función, lo que significa que solo se llamará una vez (con el valor inicial), creo. Para solucionar esto y registrar cada vez que cambia el valor de currentWeather , puede hacer esto en su lugar: React.useEffect(() => { console.log(currentWeather?.location?.name) }, [currentWeather])