React Custom Hook: useSubmit

Murat Catal
Oct 13, 2019 · 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.

New JavaScript + Web Development articles every day.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store