2

I've been using Open Weather's Api to fetch data and store it into a saved state in React JS in order to call the saved state and render the actual weather data on my web app. Here's the problem, I can console.log the api data that is stored in the function variable with no problem, I can even pass the api data directly into the state, and then into my web app. However, when I try to pass the api data into a variable, and then save that to the state and render it, I get an error of "TypeError: Unable to get property 'temp' of undefined or null reference". The reason I do not understand that is if I take that same "null reference" snippet, and try to console log it inside the function, it returns the data! What exactly am I doing wrong?

I'm still relatively new to ReactJS so to gain a better understanding to React JS api calls I read through Ethan Jerrel's article (which actually did help me alot) on fetching api data in react: https://blog.hellojs.org/fetching-api-data-with-react-js-460fe8bbf8f2

As Well as the following previous stack overflow questions concerning similar problems:

-Basic open weather api problem Open weather API

-problem with ajax call using open weather api Open Weather data in React using Ajax

-Updating set state with api data updating set state in api call react

This is my code:

   import React, { Component } from 'react';
// import logo from '../logo.svg';
import '../App.css';

class Main extends Component {

  constructor(props) {
    super(props);
    this.state = {
      kyoto: [],
      kyotoMainWeather: [],
      kyotoTemp: [],
      kyotoDescription: [],

    }
  }
  componentDidMount() {
 this.fetchData();


}

fetchData(){
  fetch('https://api.openweathermap.org/data/2.5/weather?q=kyoto&units=imperial&APPID=63dd0d75cb039f76bb9b092405a90895')
  .then(response => response.json())
  .then(data => {
     console.log(data); //returns api data in object with no error

     var kyoto = data; //stores api data in var
     console.log(kyoto); // returns api data in object with no error

     var kyotoMainWeather = data.weather[0].main; //stores api data in var
     var kyotoTemp = data.main.temp; //stores api data in var
     var kyotoDescription = data.weather[0].description; //stores api data in var

      this.setState({kyoto: kyoto}); //stores api object data in saved state
      this.setState({kyotoMainWeather: kyotoMainWeather}); //stores api object data in saved state
      this.setState({kyotoTemp: kyotoTemp}); //stores api object data in saved state
      this.setState({kyotoDescription: kyotoDescription}); //stores api object data in saved state


  })
  .catch(error => console.log('parsing failed', error))


}



  render() {
    return (
      <div className="Body">
      <div className="row">
      <div className="col-sm-6">

      <div className="card bg-dark text-white">
  <img className="card-img" src={"https://images.pexels.com/photos/219000/pexels-photo-219000.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"} alt="Weather Card"/>
  <div className="card-img-overlay d-flex align-items-end">
  <div className="card-row">
  <div className="temperature-city-container">
    <h5 className="weather-card-text">{this.state.kyoto.main.temp}&#176;</h5> // This is an actual data call which returns null in my web app, but when I console.log(kyoto.main.temp) it returns!
    <p className="temperature-undertext">Kyoto, Japan</p>
    </div>
    <p className="weather-card-secondary-text">{this.state.kyotoTemp}</p> // this returns the data with no error

    <p className="weather-card-secondary-text">{this.state.kyoto.main.temp}</p> // this is the same call (in theory) as the above "this.state.kyotoTemp" however it returns null, but when I console.log(kyoto.main.temp) it returns!
    </div>
  </div>
</div>

      </div>

      </div>

      </div>
    );
  }
}

export default Main;

1 Answer 1

1

Looks like you're rendering your component before the data is fetched. Try giving defaults to the data passed to the component, or check if data exists before rendering. Something like:

<h5 className="weather-card-text">
    {this.state.kyoto && this.state.kyoto.main && this.state.kyoto.main.temp}&#176;
</h5>

So you check that kyoto and then kyto.main exists on the state before trying to call properties from them.

5
  • I just attempted running that and received the same error "TypeError: Unable to get property 'temp' of undefined or null reference", did you mean perhaps running some kind of if statement? Apr 10, 2018 at 3:20
  • What about {this.state.kyoto && this.state.kyoto.main && this.state.kyoto.main.temp}? That's checking the existence of each parent in the hierarchy, and returning true when they all exist. Apr 10, 2018 at 3:23
  • That worked!!!! Thank you so much!!! How exactly does that work??? And why does it return the temp value? I don't see a "return" statement in there, yet it still returns it? How is that possible? Apr 10, 2018 at 3:27
  • 1
    You're welcome! When looking for a property value that's deep in a tree-like structure, one often has to check whether intermediate nodes exist. This is why there is a proposal for a syntax to do this in a (debatably) cleaner way. My immediate guess is that react is re-rendering that particular component before each individual step in the tree gets loaded, whereas the variables you stored the result in already have that data on each re-render. Apr 10, 2018 at 3:33
  • 1
    That makes sense!! you totally helped me out a lot! Thank you so much!!! Apr 10, 2018 at 3:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.