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: {}

.then(function(response) {
return response.json();
.then(function(result) {
return this.state;

componentDidMount: function() {

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

The problem I have is that
returns the data object empty but when I try to log
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