Created
October 24, 2020 20:33
-
-
Save jhannes/42fa6fba6eff30506148c5a23b22e063 to your computer and use it in GitHub Desktop.
Zombie spinner killer
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
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