I try to build a React hook for handling confirming action like responding to a dialog. The hook function can receive an optional option that contains callback functions for on cancel or on confirm. But because this function can either be async, normal or throwing errors. So I'm not quite sure what is the best approach to execute it.
import { useState } from 'react';
function useConfirmDialog(options) {
const usageOptions = options || {
onConfirm: () => {
// this function can either be a normal function,
// async function or throws errors
},
onCancel: () => {
// like onConfirm
},
};
const { onConfirm, onCancel } = usageOptions;
const [isOpen, setIsOpen] = useState(false);
function open() {
setIsOpen(true);
}
function close() {
setIsOpen(false);
}
function confirm() {
// how to correctly call onConfirm() so that
// it only calls close() if it's not throwing error
// also, how can we await if it is an async function
}
function cancel() {
// same with confirm
}
return {
open,
close,
isOpen,
confirm,
cancel,
};
}
export default useConfirmDialog;