'use client';
import { useMemoizedFn } from 'ahooks';
import { useState } from 'react';

/**
 * 异步函数hook, 自动托管loading状态
 * @param fn 异步函数
 * @returns 异步函数执行结果
 */
export const useAsyncFn = <T extends (...args: any[]) => Promise<any>>(
  fn: T
): {
  loading: boolean;
  run: T;
} => {
  const [loading, setLoading] = useState(false);

  const run = useMemoizedFn(async (...args: Parameters<T>) => {
    setLoading(true);
    try {
      const result = await fn(...args);
      return result;
    } finally {
      setLoading(false);
    }
  }) as T;

  return {
    loading,
    run,
  };
};
