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'));
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'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With