import { useCallback, useState } from 'react';
/**
 *    Use async fetch hook
 *    The fetchFunc should be a function that returns a promise
 *    The fetchhFunc can return pormise<void>, where the state of the parent component will be updated inside
 *    the fetchFunc itself, or do something else
 *    @param fetchFunc - The function that returns a promise, which could be promise<void>
 *    @returns {execute: () => Promise<void>, isLoading: boolean} -
 *    execute: Execute the fetchFunc callback passed in the hook
 *    isLoading: Whether the fetchFunc is loading
 *
 * */
const useAsyncFetch = ({ fetchFunc }: { fetchFunc: () => Promise<any> }) => {
  const [isLoading, setIsLoading] = useState(false);
  /*
   * Use async fetch hook
   *    Execute the fetchFunc callback passed in the hook
   * */
  const execute = useCallback(async () => {
    setIsLoading(true);
    const response = await fetchFunc();
    setIsLoading(false);
    return response;
  }, [fetchFunc]);
  return { execute, isLoading };
};
export default useAsyncFetch;
