Created
August 5, 2020 22:08
-
-
Save frekw/e513f98321c89205ade992e250e2caaf to your computer and use it in GitHub Desktop.
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 useAsync() { | |
const [fn, setFn] = useState(null); | |
const [state, setState] = useState({ | |
loading: false, | |
data: null, | |
error: null | |
}); | |
const lastCallId = useRef(0); | |
useEffect(() => { | |
let awaiting; | |
if (!fn) { | |
return () => {}; | |
} | |
const callId = ++lastCallId.current; | |
setState(s => ({ ...s, loading: true })); | |
awaiting = makeCancelable(fn()); | |
awaiting.promise.then( | |
function(res) { | |
if (callId !== lastCallId.current) return; | |
setState({ data: res, error: null, loading: false }); | |
}, | |
function(err) { | |
if (callId !== lastCallId.current) return; | |
setState({ data: null, error: err, loading: false }); | |
} | |
); | |
return () => { | |
if (awaiting) { | |
awaiting.cancel(); | |
} | |
}; | |
}, [fn]); | |
return [x => setFn(_ => x), state]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment