Can't access Javascript object within React Component

can definition
can verb
can synonym
can.'' acronym
meaning of can in hindi
can band
can pronunciation
can is a verb or noun

So, I'm getting stuck into React and it's already making me scratch my head..

I am grabbing some API data like and trying to access any particular index or loop through - whatever I do, it does not seem to work!

Here is the main component:

class App extends React.Component {
const CityListNames = ['Peterborough', 'Manchester', 'Brighton', 'Liverpool', 'Cardiff'];

  constructor(props) {

    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: []
    };

  }

  // Fire our function below on app load
  componentDidMount() {
    this.getWeather();
  }

  // getWeather - make api call
  getWeather = () => {

    let results = [];

    // Loop through our cities list here to gather data 
    // We will then push this into this.state.results
    CityListNames.forEach(function (name) {

      let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
      let data;

      // get api data  
      fetch(api_url)
      .then(res => res.json())
      .then(
        (result) => {
          results.push(result); 
          console.log(result[0]);   
        },
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      );    

    });    

    this.setState({
      isLoaded: true,
      items: results
    }); 



  }  

  render() {
    const { error, isLoaded, items } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <div className="weather-app">

        </div>
      );
    }  
  }
}

export default App;

When I use console.log(result[0]); it simply outputs as "undefined" in the console.

I am trying to assign all values to the results variable and then push it to the state.

When I do console.log(items) it shows all items as well which is very odd.

API data

Any help would be deeply appreciated!

Thanks

You have to wait for all of your api requests to resolve before setting your state, so instead of using forEach, use map and then return a promise of the date like so:

getWeather = () => {

    // Loop through our cities list here to gather data 
    // We will then push this into this.state.results
    Promise.all(CityListNames.map(function (name) {

      let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;

      return fetch(api_url)
      .then(res => res.json());

    })).then((results) => {
      this.setState({
        isLoaded: true,
        items: results
      }); 
    }).catch((error) => {
      this.setState({
        isLoaded: true,
        error
      });
    });
  }  

Can, VerbEdit. can (third-person singular simple present can, present participle -, simple past could, past participle (obsolete except in adjectival use) couth). Can definition, to be able to; have the ability, power, or skill to: She can solve the problem easily, I'm sure. See more.

Try this.

class App extends React.Component {
  const CityListNames = ['Peterborough', 'Manchester', 'Brighton', 'Liverpool', 'Cardiff'];
      constructor(props) {

       super(props);
        this.state = {
          error: null,
          isLoaded: false,
          items: []
        };

      }

      // Fire our function below on app load
      componentDidMount() {
        this.getWeather();
      }

      // getWeather - make api call
      getWeather = () => {

        let self = this,
            results = [], responses = [];

        // Loop through our cities list here to gather data 
        // We will then push this into this.state.results
        CityListNames.forEach(function (name) {

          let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
          let data;

          // get api data  
          fetch(api_url)
          .then(res => {
             responses.push(res.json());
           });
        };    

        Promise.all(responses).then((values) => {
          self.setState({
            isLoaded: true,
            items: results
          });
        });// this works, because setState is called after before all promises are fulfilled 
      }    

    render() {
      const { error, isLoaded, items } = this.state;
      if (error) {
        return <div>Error: {error.message}</div>;
      } else if (!isLoaded) {
        return <div>Loading...</div>;
      } else {
        return (
          <div className="weather-app">

          </div>
        );
      }  
    }
}

export default App;

Can, can meaning: 1. to be able to: 2. used to say that you can and will do something: 3. to be allowed to: . Learn more. Define can. can synonyms, can pronunciation, can translation, English dictionary definition of can. to be able to, have the power or skill to: I can take a bus to the

Did you mean to console.log(results[0]) plural of 'result'. In your promise result is what you get after you parse the response to json. If that response does not have a key of '0' (which it shouldn't), then you will get undefined.

Edit

The issue is not that you are making an asynchronous call and then performing the synchronous action of a push and console.log. The issue is that there is a typo where you are console logging vs pushing the proper response.

fetch(api_url)
  .then(res => res.json())
  .then(
    (result) => {
      results.push(result); // <--- pushes valid response into array
      console.log(result[0]); // <--- logs undefined   
    },

The response does not have a key of "0" therefore you log undefined, but you push result (which is valid). Therefore you will get an array of proper results at the end of your calls. But you will log a bunch of "undefined" to console.

can, Can was the leading avant-garde rock group of the 70s. Can experimented with noise, synthesizers, non-traditional music, cut-and-paste techniques, and, most  can definition: 1. to be able to: 2. used to say that you can and will do something: 3. to be allowed to: . Learn more.

1.fetch: works asynchronously, therefore when you assign to the state the value of results this will be an empty array.

this.setState({
        isLoaded: true,
        items: results
      });    

the previous code must go in the fetch result

class App extends React.Component {
cityListNames = ['Peterborough', 'Manchester', 'Brighton', 'Liverpool', 'Cardiff']; // this is one of the changes

  constructor(props) {

    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: []
    };

  }

  componentDidMount() {
    this.getWeather();
  }


  getWeather = () => {

    let results = [];

    this.cityListNames.forEach(function (name) { //this is one of the changes

      let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
      let data;

      fetch(api_url)
      .then(res => res.json())
      .then((result) => {
          results.push(result); 
          this.setState({ // this is one of the changes
            isLoaded: true,
            items: results
          });    
        },
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      );    

    });    

  }  

  render() {
    const { error, isLoaded, items } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <div className="weather-app">

        </div>
      );
    }  
  }
}

export default App;

CAN, 1.4Used to indicate that something is typically the case. 'antique clocks can seem out of place in modern homes'. More example sentences. 110 synonyms of can from the Merriam-Webster Thesaurus, plus 97 related words, definitions, and antonyms. Find another word for can. Can: to bring (as an action or operation) to an immediate end.

The Official CAN / Spoon Records Website, can definition: The definition of a can is a container normally made of metal with a lid. (noun) An example of can is what tuna comes in. A Controller Area Network (CAN bus) is a robust vehicle bus standard designed to allow microcontrollers and devices to communicate with each other's applications without a host computer. It is a message-based protocol , designed originally for multiplex electrical wiring within automobiles to save on copper, but can also be used in many other

Can, can. (kæn). n. 1. a container, esp for liquids, usually of thin sheet metal: a petrol can;  Can (stylised as CAN) was a German experimental rock band formed in Cologne in 1968 by the core quartet of Holger Czukay (bass, tape editing), Irmin Schmidt (keyboards), Michael Karoli (guitar), and Jaki Liebezeit (drums).

Can dictionary definition, can ​Definitions and Synonyms ​‌‌. ​noun countable. UK /kæn/  We would like to show you a description here but the site won’t allow us.

Comments
  • fetch() is asynchronous. What you see in console is not a snapshot. It will represent updates even after it is logged
  • Possible duplicate of How do I return the response from an asynchronous call?
  • Do not post images of code or errors! Images and screenshots can be a nice addition to a post, but please make sure the post is still cle ar and useful without them. If you post images of code or error messages make sure you also copy and paste or type the actual code/message into the post directly.