Yukina Spoonatte Yukina Spoonatte - 4 years ago 190
React JSX Question

Acces this.state variables in React

I have the following code in react :

getInitialState: function() {
var state= {
data: {}
};

fetch(this.props.dataurl)
.then(function(response) {
return response.json();
})
.then(function(result) {
this.setState({data:result});
}.bind(this));
return this.state;

},
componentDidMount: function() {
console.log(this);
console.log(this.state);
}


So in the
getInitialState
function I initialize the state variable data with results from fetch and then I want to access the data variable in the second function
componentDidMount
.

The problem I have is that
this.state
returns the data object empty but when I try to log
this
I'm getting the data variable with the data in it.

So why I'm having this behavior and how can I solve it?

Answer Source

componentDidMount does not guarantee that the async fetch has been completed.

You should define componentDidUpdate that will be called when the state has been changed, so that you can do anything with that new data.

componentDidUpdate(object prevProps, object prevState)

See React Lifecycle.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download