React Custom Hook: useSubmit
Oct 13, 2019 · 2 min read
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.