Last active
May 8, 2019 05:18
-
-
Save gaperton/bcd6eb4dad445ecd07850e9b7d63f76b to your computer and use it in GitHub Desktop.
This file contains hidden or 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 useIO( fun, condition = [] ) { | |
// Counter of open I/O requests. If it's 0, I/O is completed. | |
// Counter is needed to handle the situation when the next request | |
// is issued before the previous one was completed. | |
const $isReady = useSafeLink( null ); | |
useEffect(()=>{ | |
// function in set instead of value to avoid race conditions with counter increment. | |
$isReady.set( x => ( x || 0 ) + 1 ); | |
fun().finally(() => $isReady.set( x => x - 1 )); | |
}, condition); | |
// null is used to detect the first render when no requests issued yet | |
// but the I/O is not completed. | |
return $isReady.value === null ? false : !$isReady.value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment