Q:

How to get an item from an array in JSON in ReactJS?

I am trying to get an item "icon" from "weather" form following JSON
{
  "coord": {
    "lon": 14.33,
    "lat": 49.94
  },
  "weather": [{
    "id": 800,
    "main": "Clear",
    "description": "clear sky",
    "icon": "01d"
  }]
}

I can't figure out how to exctract an item which is in array through render method.
My code is:
class Weather extends React.Component {
  constructor() {
    super();
    this.state = {
      'items': []
    }
  }

  componentDidMount() {
    this.getItems();
  }

  getItems() {
    fetch('http://api.openweathermap.org/data/2.5/weather?lat=49.9415967&lon=14.3316786&appid=ed62e370682cc9e4144620905eff37e4')
    .then(results => results.json())
    .then(results => this.setState ({'items': results}));
  }

  render() {
    return (
        <div>
            <h1>here should be an icon..</h1>
            {this.state.items.weather.map(function(weather, index) {
                return <h3 key={index}>{weather.icon}</h3>
            })}
        </div>
    );
  }
}

I actually used this question here: Get access to array in JSON by ReactJS ...which got me this far, but still can't make it working...

A:

Your weather array is not set until your fetch request is complete, so this.state.items.weather.map in your render method will result in an error.
You could give weather an empty array as default value.
class Weather extends React.Component {
  constructor() {
    super();
    this.state = {
      items: {
        weather: []
      }
    };
  }

  componentDidMount() {
    this.getItems();
  }

  getItems() {
    fetch(
      "http://api.openweathermap.org/data/2.5/weather?lat=49.9415967&lon=14.3316786&appid=ed62e370682cc9e4144620905eff37e4"
    )
      .then(results => results.json())
      .then(results => this.setState({ items: results }));
  }

  render() {
    return (
      <div>
        <h1>here should be an icon..</h1>
        {this.state.items.weather.map(function(weather, index) {
          return <h3 key={index}>{weather.icon}</h3>;
        })}
      </div>
    );
  }
}

