ajafari
ajafari

Reputation: 193

React Native - setState doesn't work in constructor

Here is my code:

I want to set functions results which I get them as promises to some state variables but as it seems after use this.setState in then() function it returns empty object! I checked in then() block and it contains data as it's supposed to.

class ProfileScreen extends Component{
    constructor(props){
        super(props);

        this.state = {
            profile_data: {},
            user_data: {}
        };

        this._getUserData().then(response => {
            this.setState({user_data: response});
        });
        //Empty Results
        console.log(this.state.user_data);

        this._getProfileData(this.state.user_data.id).then(response => {
            this.setState({profile_data: response});
        })
    }
}

Upvotes: 0

Views: 665

Answers (2)

Transfusion
Transfusion

Reputation: 586

In addition to what Suraj said, if _getUserData is asynchronous, perhaps doing an AJAX call, then _getProfileData must be inside the .then callback too since you depend on the user_data to fetch the profile_data.

Try this snack out: https://snack.expo.io/@transfusion/stackoverflow-53694220

It might be cleaner to just chain the promises together.

Upvotes: 1

Suraj Malviya
Suraj Malviya

Reputation: 3783

First of all you should never set your state in constructor using setState as a call to setState leads to rerendering of the view heirarchy which is not yet built to be rerendered.

A better place for doing so is componentDidMount because thats a lifecycle callback which ensures that the DOM is already rendered once and now you can update your state to see the changes in the view.

Coming to your problem, the empty result is due to the fact that the setState is asynchronous in nature, thus the console.log would have run even before the setState has updated the state.

You should rely on the second parameter of the setState which is a callback that runs post the state update.

this.setState({
   user_data: response
}, () => {
    console.log(this.state.user_data);
})

Don't do this in your constructor. Fetch your user detail in componentDidMount and then set your state as per your need

Upvotes: 2

Related Questions