Skip to content

Instantly share code, notes, and snippets.

@sibelius
Created October 31, 2019 19:17
Show Gist options
  • Save sibelius/c48a7ad2c55cdf06a15169a3d7ddb75d to your computer and use it in GitHub Desktop.
Save sibelius/c48a7ad2c55cdf06a15169a3d7ddb75d to your computer and use it in GitHub Desktop.
useSubmit hook to make sure you don't call onSubmit twice
import { useState, useRef, useCallback } from 'react';
export const useSubmit = (fun: Function) => {
const [isPending, setIsPending] = useState<boolean>(false);
const pendingRef = useRef(null);
const submit = useCallback((...args) => {
if (pendingRef.current) {
return;
}
pendingRef.current = true;
setIsPending(true);
fun.apply(this, args)
setIsPending(false);
pendingRef.current = false;
}, []);
return [
submit,
isPending,
];
};
const [onSubmit, pending] = useSubmit(() => console.log('submit'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment