Home > front end >  console.log read the previous state and not the current one
console.log read the previous state and not the current one

Time:08-24

Hi everyone i'm recently studying react native and i have a problem. After setting the status, I cannot read the current value. My code is:

export default class HomePage extends Component {
    static navigation = {}
    constructor() {
        super();
        this.state = {
            alreadyLaunched: null,
            sid: "aa"
        };
    }
    _getSid() {
        console.log("state value is: ", this.state.sid);
    }
    _setSid() {
        this.setState({
            sid: "bbb"
        }, function() {
            console.log(this.state.sid);
        })
    }
    componentDidMount() {
        AsyncStorage.getItem("alreadyLaunched").then(value => {
            if (value == null) {
                AsyncStorage.setItem("alreadyLaunched", JSON.stringify(true));
                this.setState({
                    firstLaunch: true
                });
                this._setSid();
            } else {
                this.setState({
                    firstLaunch: false
                });
                this._getSid();
            }
        })
    }
    render() {}
}

My problem is that _getSid() method print "state value is aa" and not "state value is bbb". Why?

CodePudding user response:

Update setSid to below

_setSid() {
  this.setState({
    sid: "bbb"
  }, () => {
    console.log(this.state.sid);
  });
}

Ahh setSTate is async, hence getSId prints prev value, setState has a callback func.

try this

this.setState({
  firstLaunch: false
} ,() => {
  this._getSid();
});
           

CodePudding user response:

The issue is on the ComponentDidMount method.

componentDidMount() {
  AsyncStorage.getItem("alreadyLaunched").then(value => {
    if (value == null) {
      AsyncStorage.setItem("alreadyLaunched", JSON.stringify(true));
      this.setState({
        firstLaunch: true
      });
      this._setSid();
    } else {
      this.setState({
        firstLaunch: false
      });
      this._getSid();
    }
  })
}

Here, if value is null, then it updates the sid state variable, but otherwise, it doesn't update sid. When you launch this at first time, the value is null. as a result, it goes to first clause, in this case, you can see the log you're expecting. But after that, it always goes to second clause, and there is no chance to update the sid state variable

  • Related