0

On delete click I'm calling a modal dialog, and updating the 'userid' state with corresponding userid of deleting member. setState function not updating the value. How can I achieve this in any other way.

delete click handler

handleClickDialogOpen = (userid) => {   
    this.setState((state) => {
      return {
        open: true,
        UserID: userid,

      };
    });
    console.log(this.state)
  };

and within modal dailog, on delete button i cannot get the value of userId

 <Button onClick={() => deleteSP(this.state.userID)} className={classes.agree}>
       Delete
</Button>

How can I pass the Id for 'deleteSP'

ansh
  • 115
  • 2
  • 14
  • 3
    Possible duplicate of [Why calling react setState method doesn't mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-calling-react-setstate-method-doesnt-mutate-the-state-immediately) – Jayce444 May 10 '19 at 11:45
  • can you tell me how can i modify my code? – ansh May 10 '19 at 11:56

1 Answers1

1

setState is async, you can do a console log like this example, because that function will trigger when setState is completed

handleClickDialogOpen = userid => {
    this.setState({
        open: true,
        UserID: userid,
      },
      () => console.log(this.state),
    );
  };
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
  • This Worked.!. How can I pass userID to this 'deleteSP(this.state.userID)}'. it say 'undefined' when do console.log – ansh May 10 '19 at 12:08
  • 1
    if you are trying to call that function just below the setState, it might happen that the state hasn't been populated yet, you can try calling the function the same way I provided you in the example, replacing the console.log with this.deleteSP(this.state.userId) Also, if your function deletes what it's on the state, you can get the value of the state in the function and just call ``this.deleteSP`` – ProblemsEverywhere May 10 '19 at 12:10