Last active
January 13, 2022 10:23
-
-
Save vaibhavpandeyvpz/7d1335f29fc13d7d63aaf61fa493b940 to your computer and use it in GitHub Desktop.
Reusable hook to load asynchronous data in React.
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 { useEffect, useState } from 'react'; | |
function useDataLoader(promise, options) { | |
const { autoload } = { autoload: true, ...options }; | |
const [error, setError] = useState(null); | |
const [loading, setLoading] = useState(!!autoload); | |
const [result, setResult] = useState(null); | |
function action() { | |
setLoading(true); | |
setError(null); | |
promise() | |
.then(result => setResult(result)) | |
.catch(error => setError(error)) | |
.finally(() => setLoading(false)); | |
} | |
useEffect(() => { | |
if (autoload) { | |
action(); | |
} | |
// eslint-disable-next-line | |
}, []); | |
return { action, error, loading, result }; | |
} | |
export default useDataLoader; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment