Brennan
Brennan

Reputation: 129

Passing in a callback after changing state

Currently trying to convert the React + Material UI + Firebase template found on the Material UI website. Right now I am trying (codesandbox) to open the dialog component for the Sign Up. The current setup for App.js has the function:

openDialog = (dialogId, callback) => {
  const dialog = this.state[dialogId];

  if (!dialog || dialog.open === undefined || null) {
    return;
  }

  dialog.open = true;

  this.setState({ dialog }, callback);

};

And I am trying to convert it to use hooks like such, but not sure how with the callback:

const openDialog = e => {
  setDialog({ ...dialog, [e.target.name]: true });
};

Upvotes: 0

Views: 67

Answers (1)

ravibagul91
ravibagul91

Reputation: 20755

You can call your callback in useEffect hook. You need to pass dialog.open as a dependency to the useEffect hook which will only run when dialog.open changes,

useEffect(() => {
  if (dialog.open) {
    callback();    //This is where you call your callback function
  }
},[dialog.open,callback])  //pass your function as dependency

Demo

Upvotes: 1

Related Questions