Roy Z
Roy Z

Reputation: 117

React- this shows populated state but this.state is empty

I have a component that renders the user's friends, and I need to get information about them. I have the function below called in componentDidMount that gets information about the friends and puts the data in state:

getFriends = ids =>{
    const config = {
        headers: {
            token: localStorage.getItem('token')
        }
    };

    axios.post('http://localhost:8082/api/friend/getAll', {friends: ids}, config)
        .then(res=>this.setState({friends: res.data.friends}))
        .catch(err=>console.log(err));
    console.log(this);
    console.log(this.state)
}

The problem is this shows the correctly populated state:

enter image description here

But this.state shows an "empty" state:

enter image description here

I am confused as to why those 2 are different. It shouldn't be a binding issue because I'm using arrow functions. Any help would be appreciated!

Upvotes: 2

Views: 356

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281656

State updates are asynchronous and also the console values are resolved when you expand the object

So for instance when you log this and later when you try to expand the printed object, the state is evaluated and it shows you the updated state since by that time the state got updated.

However when you log this.state the updated value is not shown since the object is already printed on your screen

Please read

Value was evaluated just now with console.log on JavaScript object

setState doesn't update the state immediately

You can see the updated value of state if you log it in the callback function of setState

getFriends = ids =>{
    const config = {
        headers: {
            token: localStorage.getItem('token')
        }
    };

    axios.post('http://localhost:8082/api/friend/getAll', {friends: ids}, config)
        .then(res=>this.setState({friends: res.data.friends}, () => {
             console.log(this.state);
         }))
        .catch(err=>console.log(err));
}

Upvotes: 4

Related Questions