-1

I'm trying to log the updated values of state after setState. But they are not updating. can anyone tell me why? The updated values of states can be seen in render function but not in the tokenAccess() method.

import React, { Component } from 'react';

class Login extends Component {
    constructor(props){
        super(props);
        this.authUrl=this.authUrl.bind(this);
        this.tokenAccess=this.tokenAccess.bind(this);
        this.state = {
            access_token:'',
            token_type:'',
            expires_in:''
        }
    }

    tokenAccess(){
        const hash = window.location.hash.substring(1);
        const hashArr = hash.split(/[=&]/);
        console.log(hashArr);
        this.setState({
            access_token: hashArr[1],
            token_type: hashArr[3],
            expires_in: hashArr[5],
        })
        console.log(this.state);
    }

    componentDidMount(){
        this.tokenAccess();
    }

    render() {
        return (
            <div>
                <a href={this.authUrl()}>LOGIN</a>
                <div>
                    {
                        this.state.access_token
                    }

                </div>
            </div>
        )
    }
}

export default Login;
  • 2
    Possible duplicate of [React slow setState at console.log](https://stackoverflow.com/questions/45622879/react-slow-setstate-at-console-log) – rlemon Sep 22 '19 at 12:29
  • 1
    ugh, should have been https://stackoverflow.com/questions/41278385/setstate-doesnt-update-the-state-immediately – rlemon Sep 22 '19 at 12:30
  • 1
    Possible duplicate of [setState doesn't update the state immediately](https://stackoverflow.com/questions/41278385/setstate-doesnt-update-the-state-immediately) – Agney Sep 22 '19 at 12:41
  • 1
    setState is asynchronous, it takes some time to mutate the state. Hence it may not be available immediately. – Pawan Jangid Sep 22 '19 at 12:50

2 Answers2

1

You need to use callback, change your setstate like this

  this.setState({yourdata:"newdata"},
   ()=>console.log(this.state.yourdata))

If your state is still empty then maybe your hashArr has problem and you should check it out

Hope you get the idea and it works for you

behzad
  • 801
  • 3
  • 15
  • 33
0

setState is an asyncronous method, which means that the effect is not immediate. That is why you should pass the code you want to execute after as second parameter (callback) : setState(updater[, callback]) (source).

tokenAccess(){
    const hash = window.location.hash.substring(1);
    const hashArr = hash.split(/[=&]/);
    console.log(hashArr);
    this.setState({
        access_token: hashArr[1],
        token_type: hashArr[3],
        expires_in: hashArr[5],
    }, () => {                   // This is the
        console.log(this.state); // callback as
    })                           // second parameter
}
David Alvarez
  • 1,226
  • 11
  • 23