Last active
November 1, 2019 01:52
-
-
Save elsangedy/e71b9cf42ed571d144cca443a1fa70ab to your computer and use it in GitHub Desktop.
useSubmit
This file contains hidden or 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 { useState, useCallback } from "react"; | |
export function useSubmit(fun: Function): [Function, boolean] { | |
const [pending, setPending] = useState<boolean>(false); | |
const submit = useCallback( | |
(...args) => { | |
if (pending) return; | |
const res = fun.apply(this, args); | |
if (res instanceof Promise) { | |
setPending(true); | |
res.finally(() => setPending(false)); | |
} | |
}, | |
[pending, fun] | |
); | |
return [submit, pending]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment