Skip to content

Instantly share code, notes, and snippets.

@gaperton
Last active May 8, 2019 05:18
Show Gist options
  • Save gaperton/bcd6eb4dad445ecd07850e9b7d63f76b to your computer and use it in GitHub Desktop.
Save gaperton/bcd6eb4dad445ecd07850e9b7d63f76b to your computer and use it in GitHub Desktop.
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