useAsyncState.ts 785 B

123456789101112131415161718192021222324
  1. import { useEffect, useMemo, useState } from 'react';
  2. export function useAsyncState<T>(asyncFn: () => Promise<T>, setError: Function, dependencies: unknown[]) {
  3. // Use the lazy initial state functionality of useState to assign a random ID to the API call
  4. // to track where errors come from. See useLastError.
  5. const [errorSource] = useState(() => Math.random());
  6. const [value, setValue] = useState<T>();
  7. const finalValue = useMemo(() => value ?? [], [value]);
  8. useEffect(() => {
  9. asyncFn()
  10. .then((results) => {
  11. setValue(results);
  12. setError(errorSource, undefined);
  13. })
  14. .catch((err) => {
  15. setError(errorSource, err);
  16. });
  17. // eslint-disable-next-line react-hooks/exhaustive-deps
  18. }, dependencies);
  19. return finalValue;
  20. }