Skip to content

Instantly share code, notes, and snippets.

@vaibhavpandeyvpz
Created October 13, 2021 19:15
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/5c1285fe9f3438e6de6467dcccfa4427 to your computer and use it in GitHub Desktop.
Save vaibhavpandeyvpz/5c1285fe9f3438e6de6467dcccfa4427 to your computer and use it in GitHub Desktop.
Load/preload component data statefully using React hooks.
import { useEffect, useState } from "react";
export default function useStatefulPromise(
callback: () => Promise<any>,
autoload = true
) {
const [error, setError] = useState<any>();
const [pending, setPending] = useState(true);
const [preload] = useState<boolean>(autoload);
const [result, setResult] = useState<any>();
function reload() {
setPending(true);
setError(undefined);
callback()
.then((x) => {
setResult(x);
})
.catch((err) => {
setError(err);
})
.finally(() => {
setPending(false);
});
}
useEffect(() => {
if (preload) {
reload();
}
// eslint-disable-next-line
}, []);
return { error, pending, reload, result };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment