Modals Are Promises
Kyle Parisi

Kyle Parisi @kyleparisi

About: Working on https://buildapart.io, https://fluxion.app in my spare time.

Location:
Newtown, PA
Joined:
Jun 20, 2018

Modals Are Promises

Publish Date: Nov 10 '20
6 0

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


Comments 0 total

    Add comment