Created
August 28, 2019 20:04
-
-
Save davidwallacejackson/5c6745812625669c09ebdbcbd24d040d 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
| import { useState, useEffect, useRef } from 'react'; | |
| type State<T> = { | |
| data?: T; | |
| error?: any; | |
| }; | |
| export default function useAsync<T>( | |
| getData: () => Promise<T>, | |
| deps: readonly any[], | |
| ): State<T> { | |
| const [state, setState] = useState<State<T>>({}); | |
| const promiseRef = useRef<Promise<T>>(); | |
| useEffect(() => { | |
| const promise = getData(); | |
| promiseRef.current = promise; | |
| promise | |
| .then((data) => { | |
| if (promise === promiseRef.current) { | |
| setState({ data }); | |
| } | |
| }) | |
| .catch((error) => { | |
| if (promise === promiseRef.current) { | |
| setState({ error }); | |
| } | |
| }); | |
| }, deps); | |
| return state; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment