Created
December 30, 2020 21:13
-
-
Save cheapsteak/e9a5d4c514f9c4973b824854a0156be4 to your computer and use it in GitHub Desktop.
helper for creating prompts that can be awaited on
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useCallback, useRef, useState } from "react"; | |
export const cancelledSymbol = Symbol("Cancelled"); | |
export function usePromptState< | |
PromptResults, | |
PromptFunction extends Function = () => void | |
>({ stableOnPrompt }: { stableOnPrompt?: PromptFunction } = {}) { | |
const [isOpen, setIsOpen] = useState<boolean>(false); | |
const resolveRef = useRef< | |
(data: PromptResults | typeof cancelledSymbol) => void | |
>(); | |
const rejectRef = useRef<(data?: unknown) => void>(); | |
return { | |
isOpen, | |
prompt: useCallback( | |
async (...args): Promise<PromptResults | typeof cancelledSymbol> => { | |
stableOnPrompt?.(...args); | |
setIsOpen(true); | |
return new Promise((resolve, reject) => { | |
resolveRef.current = resolve; | |
rejectRef.current = reject; | |
}); | |
}, | |
[stableOnPrompt] | |
), | |
onCancel: useCallback(() => { | |
resolveRef.current?.(cancelledSymbol); | |
setIsOpen(false); | |
}, [setIsOpen]), | |
onResolve: useCallback( | |
(resolveWith: PromptResults) => { | |
resolveRef.current?.(resolveWith); | |
setIsOpen(false); | |
}, | |
[setIsOpen] | |
), | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment