import "core-js/modules/es.array.iterator.js";
import "core-js/modules/web.dom-collections.iterator.js";
import "core-js/modules/es.promise.js";
import { useEffect } from 'react';
import useMergedState from 'rc-util/lib/hooks/useMergedState';
const useFetchData = (getData, options) => {
  const {
    onRequestError,
    effects,
    manual,
    dataSource,
    defaultDataSource,
    onDataSourceChange
  } = options || {};
  const [entity, setEntity] = useMergedState(defaultDataSource, {
    value: dataSource,
    onChange: onDataSourceChange
  });
  const [loading, setLoading] = useMergedState(options === null || options === void 0 ? void 0 : options.loading, {
    value: options === null || options === void 0 ? void 0 : options.loading,
    onChange: options === null || options === void 0 ? void 0 : options.onLoadingChange
  });
  const updateDataAndLoading = data => {
    setEntity(data);
    setLoading(false);
  };
  /** 请求数据 */
  const fetchList = async () => {
    if (loading) {
      return;
    }
    setLoading(true);
    try {
      const {
        data,
        success
      } = (await getData()) || {};
      if (success !== false) {
        updateDataAndLoading(data);
      }
    } catch (e) {
      // 如果没有传递这个方法的话，需要把错误抛出去，以免吞掉错误
      if (onRequestError === undefined) {
        throw new Error(e);
      } else {
        onRequestError(e);
      }
      setLoading(false);
    }
  };
  useEffect(() => {
    if (manual) {
      return;
    }
    fetchList();
  }, [...(effects || []), manual]);
  return {
    dataSource: entity,
    setDataSource: setEntity,
    loading,
    reload: () => fetchList()
  };
};
export default useFetchData;