import { useState, useCallback } from 'react'

/**
 * 通用异步任务处理hook
 * @param {Function} taskFn 异步任务函数
 * @returns {Object} { isLoading, error, execute }
 */
export function useAsyncTask(taskFn) {
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState(null)

  const execute = useCallback(
    async (...args) => {
      try {
        setIsLoading(true)
        setError(null)
        return await taskFn(...args)
      } catch (err) {
        setError(err)
        throw err
      } finally {
        setIsLoading(false)
      }
    },
    [taskFn]
  )

  return { isLoading, error, execute }
}
