React Custom Hook: useSubmit

Murat Catal
Oct 13 · 2 min read
End-user’s behaviours
End-user’s behaviours
Photo by John Schnobrich on Unsplash

For most of us as front-end developer, we make CRUD operations and end-users may have lots of unpredictable operations on your operations. Today, i wrote a hook just to make submit button disable until your async operation finish.

const useSubmit = submitFunction => {
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const handleSubmit = async () => {
try {
setLoading(true);
setError(null);
await submitFunction();
} catch (error) {
setError(error);
} finally {
setLoading(false);
}
};
return [handleSubmit, loading, error];
};
function App() {
const mySubmitFunction = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const rnd = Math.random() * 10;
rnd <= 5 ? resolve() : reject("Error occurred!");
}, 2000);
});
};
const [handleSubmit, loading, error] = useSubmit(mySubmitFunction);
return (
<div className="App">
<button onClick={handleSubmit} disabled={loading}>
{!loading ? "Click me" : "Loading..."}
</button>
{error && <div>{error}</div>}
</div>
);
}

What this hook makes, handles your loading and error states. If you use GraphQL, ApolloClient provide this useful informations to you but if you are calling your endpoints via RestAPI then this hook may help you.

Live example on codesandbox


If you like my articles, you can support me by clapping and following me.
I’m also on
linkedin, all invitations are welcome.

JavaScript in Plain English

Learn the web's most important programming language.

Murat Catal

Written by

Enjoys sharing!

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade