Created
October 31, 2019 19:17
-
-
Save sibelius/c48a7ad2c55cdf06a15169a3d7ddb75d to your computer and use it in GitHub Desktop.
useSubmit hook to make sure you don't call onSubmit twice
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 { 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, | |
]; | |
}; |
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
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