Skip to content

Instantly share code, notes, and snippets.

@jscodelover
Created October 31, 2019 07:39
Show Gist options
  • Save jscodelover/bb85cf27e66895a086858adc9cba83c2 to your computer and use it in GitHub Desktop.
Save jscodelover/bb85cf27e66895a086858adc9cba83c2 to your computer and use it in GitHub Desktop.
custom react hook for submit button.
import React, { useState } from "react";
import ReactDOM from "react-dom";
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 state!");
}, 2000);
});
};
const [handleSubmit, loading, error] = useSubmit(mySubmitFunction);
return (
<div>
<button onClick={handleSubmit} disabled={loading}>
{!loading ? "Click me" : "Loading..."}
</button>
{error && <div>{error}</div>}
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment