title: ReactJS: get data from api and map data
body: <p>I am learning ReactJS. In my program, I am making an API call and later mapping it.
  The data which is fetched by API call is like,
  data = [{"uid":"1", "title":"hello"},{"uid":"2", "title":"World"}]</p>
  
  <pre><code>import ImporterAPI from '../api';
  const API = new ImporterAPI();
  
  class Home extends Component {
    constructor(props) {
      super(props);
      this.state = {
        data: ''
    }}
  
    componentWillMount() {
      this.setState({ data: API.getData()}, () =&gt; {
        console.log("data fetched");
        var mapData = []
        this.state.data.map( (object, i) =&gt; {
          mapData.push(&lt;p key={i}&gt;{object}&lt;/p&gt;)
        })
    }) 
    }
  
    render() {
      return (
        &lt;div className="home"&gt;
          {this.mapData}
        &lt;/div&gt;
      )
    }
  }
  </code></pre>
  
  <p>And my API file,</p>
  
  <pre><code>import axios from 'axios';
  class API {
    getData = () =&gt; {
      axios.get('http://localhost:8005/data')
      .then(function (response) {
        if (response.status === 200 &amp;&amp; response != null) {
          var data = response.data;
          console.log(data)
          return data
        } else {
          console.log('problem');
        }
      })
      .catch(function (error) {
        console.log(error);
      });
    }
  }
  </code></pre>
  
  <p>My console.log is printing the data from API call and then I'm returning the data. Where in home component data is assigned using setState. But there is no data storing into this.state.data. It always remains undefined and I got error "TypeError: Cannot read property 'map' of undefined".</p>
  
  <p>Please guide me. How should I print API call data &amp; I would also like to know if this program is good or bad in terms of performance for making API calls or any other better way to improve performance. Thanks.</p>
  
  <p>I would appreciate help.</p>