Skip to content

Instantly share code, notes, and snippets.

@sp0033212000
Created June 25, 2021 16:19
Show Gist options
  • Save sp0033212000/88c43e04b95fbf7acad380bac58a7029 to your computer and use it in GitHub Desktop.
Save sp0033212000/88c43e04b95fbf7acad380bac58a7029 to your computer and use it in GitHub Desktop.
Async Prompt
import React, { useState, useRef, useCallback } from "react";
import CustomModal from "../component/CustomModal";
type Resolver = ((value?: unknown) => void) | null;
type Rejecter = ((reason?: any) => void) | null;
const useAsyncDialog = ({
title,
paragraph,
confirm,
cancel
}: {
title: string;
paragraph: string;
confirm: string;
cancel: string;
}) => {
const [show, setShow] = useState<boolean>(false);
const resolver = useRef<Resolver | null>(null);
const rejecter = useRef<Rejecter | null>(null);
const dialog = () =>
new Promise((res) => {
setShow(true);
resolver.current = function () {
resolver.current = null;
setShow(false);
res(true);
};
rejecter.current = function () {
rejecter.current = null;
setShow(false);
res(false);
};
});
const AsyncPrompt = useCallback<React.FC>(
() => (
<CustomModal
show={show}
handleClose={() => rejecter.current?.()}
handleConfirm={() => resolver.current?.()}
title={title}
paragraph={paragraph}
confirm={confirm}
cancel={cancel}
/>
),
[title, paragraph, confirm, cancel, show]
);
return { dialog, AsyncPrompt };
};
export default useAsyncDialog;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment