Created
October 13, 2021 19:15
-
-
Save vaibhavpandeyvpz/5c1285fe9f3438e6de6467dcccfa4427 to your computer and use it in GitHub Desktop.
Load/preload component data statefully using React hooks.
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"; | |
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