React — await user input/confirmation

Dave Teu
2 min readDec 8, 2020

A replacement for for window.confirm() — HOOK STYLE!

Developing a app, dealing with CRUD means we often need to deal with a lot of user’s delete, and we need to provide a way to let user confirm deletion.

window.confirm() — This is the typical way of using the browser’s build in confirmation box.

if (window.confirm("Do you really want to leave?")) { 
window.open("exit.html", "Thanks for Visiting!");
}

What if we want to present a custom confirmation box with our fancy models?

The answer is Promises + Hooks.

These codes are very simple, but in my situation, very useful.

A very handy promise create function that we can call it at one place, and resolve it somewhere else. It sounds confusing isn’t it? Lets get down to coding and you will understand better how promises work in this instance.

Next up we create a useConfirm hook. This is the entire source of the hook.

I use material-ui, but you can use your own codes to write the model.

Basically the hook contains two main function ;

  1. getConfirmation — a function that toggles the model, creates a promise ( line 9), and return the promise ( line 13 ) to the caller.

2. Confirmation — a function that simply returns a model with 2 buttons — OK / Cancel. When click, these buttons will either resolve true/false, by using the resolver returned from createPromise. ( line 18 of useConfirm.js )

Using the hook.

A simple component above, renders a simple single button which calls the onDelete() function.

Notice this line?

const status = await getConfirmation()

In our useConfirmation hook, we created a pending promise, the promise is returned here, and your app can not do anything but to wait. Your app will now be waiting for the user to click either the OK or Cancel button, which will in turn return the promise’s resolver() function.

With the status from user confirmed, you can now get down to do whatever you need to process the request.

Try it on codesandbox.

Now you have a nice confirmation box, what other hooks would you be interested to write?

(image provided by www.freepik.com)

--

--