react-async-ui
Version:
Asynchronous React hooks to manage modal UI state
28 lines (27 loc) • 1.09 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.useAsyncModalState = useAsyncModalState;
const react_1 = require("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
*/
function useAsyncModalState() {
const closedState = { isOpen: false, props: null };
const [state, setState] = (0, react_1.useState)(closedState);
const showModal = (0, react_1.useCallback)((value) => {
const promise = new Promise((resolve, reject) => setState({
isOpen: true,
props: { value, resolve, reject },
}));
return promise.finally(() => setState(closedState));
}, []);
return [state, showModal];
}
;