skip to Main Content

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?

2

Answers


  1. 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();
    });
               
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search