Skip to content

Instantly share code, notes, and snippets.

@vaibhavpandeyvpz
Last active January 13, 2022 10:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vaibhavpandeyvpz/7d1335f29fc13d7d63aaf61fa493b940 to your computer and use it in GitHub Desktop.
Save vaibhavpandeyvpz/7d1335f29fc13d7d63aaf61fa493b940 to your computer and use it in GitHub Desktop.
Reusable hook to load asynchronous data in React.
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