36 lines
1.0 KiB
JavaScript
36 lines
1.0 KiB
JavaScript
import { useState } from 'react'
|
|
import ConfirmDialog from '../components/ConfirmDialog'
|
|
|
|
// Promise-based drop-in for window.confirm:
|
|
// const [confirm, confirmDialog] = useConfirm()
|
|
// if (!(await confirm({ title: 'Delete it?', confirmLabel: 'Delete', danger: true }))) return
|
|
// and render {confirmDialog} somewhere in the component. For a confirmation
|
|
// that also shows progress while the action runs, render <ConfirmDialog>
|
|
// directly instead.
|
|
export function useConfirm() {
|
|
const [request, setRequest] = useState(null)
|
|
|
|
function confirm(options) {
|
|
return new Promise((resolve) => setRequest({ ...options, resolve }))
|
|
}
|
|
|
|
function settle(result) {
|
|
request.resolve(result)
|
|
setRequest(null)
|
|
}
|
|
|
|
const dialog = request ? (
|
|
<ConfirmDialog
|
|
title={request.title}
|
|
confirmLabel={request.confirmLabel}
|
|
danger={request.danger}
|
|
onConfirm={() => settle(true)}
|
|
onCancel={() => settle(false)}
|
|
>
|
|
{request.message}
|
|
</ConfirmDialog>
|
|
) : null
|
|
|
|
return [confirm, dialog]
|
|
}
|