Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - this.state is null inside render when getting data from API

I am trying to learn react by making a simple app where I am trying to get data in json format from the sever and then rendering it to the view. The problem is that I am getting an error where it says that this.state.data is null. How do I solve this problem? The code:

class App extends React.Component {

  constructor() {
    super();
    //Query data
    fetch('http://localhost:8080/api?access_token=56d847accb86bddc243d4b93')
      .then(response => response.json())
      .then((data) => {
        this.setState({
          data: data
        })

      })
      .catch(err => console.error('Error ', err.toString()));

  }

  getInitialState() {
    return {
      data: {}
    };
  }

  render() {

    return (
      <h1>{this.state.data}</h1>
      );

  }
}

ReactDOM.render(<App/>, document.getElementById('app'));
like image 640
onurhb Avatar asked Mar 06 '16 23:03

onurhb


1 Answers

When using ES6 classes as components, there is no getInitialState method invoked.
Instead, set state on actual instance in constructor.

class App extends React.Component {

  constructor() {
    super();

    this.state = {
      data: {}
    };

    fetch('http://localhost:8080/api?access_token=56d847accb86bddc243d4b93')
      .then(response => response.json())
      .then(data => this.setState({ data }))
      .catch(err => console.error('Error ', err.toString()));

  }

  render() {
    return <h1>{this.state.data}</h1>;
  }
}

ReactDOM.render(<App/>, document.getElementById('app'));
like image 100
Andreyco Avatar answered Oct 09 '22 15:10

Andreyco