0
votes

I am trying to access this.state inside this.setState after a state is updated. I want user info to be set to state then from that source of truth wanted to save that user data into local storage

setUserInfo = userInfo => {
  this.setState(
    { username: userInfo.userName, password: userInfo.userPass },
    prevState => {
      //trying to access this.state but unable to
      console.log(prevState);
      // or
      console.log(this.state.username);
    }
  );
};

I know that this could code could do it but will the second setstate be confirm to run after the first setState?

setUserInfo = userInfo => {
  this.setState({ username: userInfo.userName, password: userInfo.userPass });
  this.setState(prevState => {
    prevState;
  });
};
2
you can use userInfo.userName inside call function instead of this.state.username - Jatin Parmar
doesnt that defeat the purpose of single source of truth? - Claude
What does 'unable to' mean? Please, provide stackoverflow.com/help/mcve that can replicate the problem. It's expected that prevState is updated state inside a callback. will the second setstate be confirm to run after the first setState? - it will, but you don't need second setState. - Estus Flask

2 Answers

1
votes

did you bind the function

inside your constructor() bind the function

this.handleClick = this.handleClick.bind(this)

handleClick() {
    this.setState({ status: 2 }, () => {
      console.log(this.state);
    });
  }

Actually this should work

0
votes

this inside the setState() function refers to methods of setState so differentiate these two this's. Set var that = this so you can use it like that.state.username

var that = this;

this.setState(
  { username: userInfo.userName, password: userInfo.userPass },
  prevState => {
    //tring to access this.state.username but unable to
    console.log(prevState.username, that.state.username);
  }
);