DEV Community

Cover image for Modals Are Promises
Kyle Parisi
Kyle Parisi

Posted on

Modals Are Promises

Can modals be treated like promises

The answer is yes. I can't count how many times I've coded a confirmation modal. Every time I've been unhappy by the extra state management required to handle the open and close actions. There must be a better way. Promises are a natural resource for control flow. Since a modal is almost always dictated by a user action, promises are a nice pattern.

Here is the tl;dr

// get some context for the modal
const thingContext = {count: 109}
const userAction = new Promise((resolve, reject) => {
  // show the modal
  setDialog({resolve, reject, context: thingContext})
})
try {
  await userAction;
} catch {
  // negative action flow
  setLoading(false);
  setDialog(false);
  return false;
}
// positive action flow
Enter fullscreen mode Exit fullscreen mode

Alt Text


Top comments (0)