Created
October 31, 2019 07:39
-
-
Save jscodelover/bb85cf27e66895a086858adc9cba83c2 to your computer and use it in GitHub Desktop.
custom react hook for submit button.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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