Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent multiple form submissions in reactjs

Tags:

reactjs

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 image 976
handsome Avatar asked Oct 28 '25 10:10

handsome


1 Answers

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>;
}
like image 127
kmui2 Avatar answered Oct 31 '25 01:10

kmui2