Skip to content

Instantly share code, notes, and snippets.

@elsangedy
Last active November 1, 2019 01:52
Show Gist options
  • Save elsangedy/e71b9cf42ed571d144cca443a1fa70ab to your computer and use it in GitHub Desktop.
Save elsangedy/e71b9cf42ed571d144cca443a1fa70ab to your computer and use it in GitHub Desktop.
useSubmit
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