Skip to content

Instantly share code, notes, and snippets.

@jhannes
Created October 24, 2020 20:33
Show Gist options
  • Save jhannes/42fa6fba6eff30506148c5a23b22e063 to your computer and use it in GitHub Desktop.
Save jhannes/42fa6fba6eff30506148c5a23b22e063 to your computer and use it in GitHub Desktop.
Zombie spinner killer
function useLoader<T>(
loadingFunction: () => Promise<T>,
deps: DependencyList[] = []
) {
const [data, setData] = useState<T | undefined>();
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | undefined>();
async function reload() {
setData(undefined);
setLoading(true);
setError(undefined);
try {
setData(await loadingFunction());
} catch (error) {
setError(error);
} finally {
setLoading(false);
}
}
useEffect(() => {
reload();
}, deps);
return { data, loading, error, reload };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment