my app has multiple forms and I'm adding this everywhere
const [submitted, setSubmitted] = useState(false)
const onSubmit = (e) => {
if (submitted) {
return;
}
setSubmitted(true)
e.preventDefault()
console.log('submitted!')
}
<form onSubmit={ (e) => onSubmit(e) }>...</form>
is there a more efficient way to do this for all forms? appreciate your guidance.
Like what @goto1 mentioned in a comment, you may create a custom hook to use for a cleaner and reusable look. Here's my take on a custom hook called useCbOnce which calls any event callback once:
const useCbOnce = (cb) => {
const [called, setCalled] = useState(false);
// Below can be wrapped in useCallback whenever re-renders becomes a problem
return (e) => {
if (!called) {
setCalled(true);
cb(e);
}
}
}
const MyForm = (props) => {
const handleSubmit = useCbOnce((e) => {
e.preventDefault()
console.log('submitted!')
});
return <form onSubmit={handleSubmit}>...</form>;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With