Last active
April 29, 2024 09:55
-
-
Save artembykov/b4fc874070df544684231a4dc500d762 to your computer and use it in GitHub Desktop.
React hook for async operations
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
import { useCallback, useEffect, useState } from "react"; | |
export default (asyncFunction, dependencies) => { | |
const memoizedAsyncFunction = useCallback(asyncFunction, dependencies); | |
const [resultGetter, setResultGetter] = useState(() => () => { }); | |
useEffect(() => { | |
const controller = new AbortController(); | |
const signal = controller.signal; | |
memoizedAsyncFunction(signal).then( | |
result => { | |
return () => result; | |
}, | |
error => { | |
return () => { throw error }; | |
}, | |
).then(getter => { | |
if (!signal.aborted) { | |
setResultGetter(() => getter); | |
} | |
}); | |
return () => controller.abort(); | |
}, [memoizedAsyncFunction]); | |
return resultGetter; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Description
useAsync
returns a getter function, which should be used to obtain the actual outcome of an async operation.Getter function behavior mimics states of a Promise:
undefined
Example
The following React component fetches weather data for specific locations from public API: