UNPKG

react-async-ui

Version:

Asynchronous React hooks to manage modal UI state

25 lines (24 loc) 955 B
import { useCallback, useState } from 'react'; /** * Manages the state of a modal UI element that can be invoked asynchronously * using the returned `showModal` callback. * * @remarks * The `TValue` and `TResult` type parameters indicate the type of the argument to * `showModal` and the type of its return value, respectively. Both default to `void`, * i.e., a modal that takes no arguments and returns no value upon completion. * * @returns Array with `state` and `showModal` elements */ export function useAsyncModalState() { const closedState = { isOpen: false, props: null }; const [state, setState] = useState(closedState); const showModal = useCallback((value) => { const promise = new Promise((resolve, reject) => setState({ isOpen: true, props: { value, resolve, reject }, })); return promise.finally(() => setState(closedState)); }, []); return [state, showModal]; }