import { useCallback, useEffect, useState } from 'react';

// Loads a value once, and again on demand (after it has been changed). `load` must not change between renders:
// pass a function defined outside the component.
export function useRemoteData<T>(load: () => Promise<T | null>): {
  data: T | null
  loading: boolean
  failed: boolean
  reload: () => Promise<void>
} {
  const [data, setData] = useState<T | null>(null);
  const [loading, setLoading] = useState(false);
  const [failed, setFailed] = useState(false);

  const reload = useCallback(async(): Promise<void> => {
    setLoading(true);
    try {
      setData(await load());
      setFailed(false);
    } catch (error) {
      setFailed(true);
    } finally {
      setLoading(false);
    }
  }, [load]);

  useEffect(() => {
    reload();
  }, [reload]);

  return { data, loading, failed, reload };
}
