Skip to content

Instantly share code, notes, and snippets.

@davidwallacejackson
Created August 28, 2019 20:04
Show Gist options
  • Select an option

  • Save davidwallacejackson/5c6745812625669c09ebdbcbd24d040d to your computer and use it in GitHub Desktop.

Select an option

Save davidwallacejackson/5c6745812625669c09ebdbcbd24d040d to your computer and use it in GitHub Desktop.
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