"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.usePromiseState = usePromiseState;
var _react = require("react");
var _bexCore = require("@wix/bex-core");
var _once = _interopRequireDefault(require("lodash/once"));
function usePromiseState(_promiseFn, {
  errorMonitor,
  onError
}) {
  const [status, setStatus] = (0, _react.useState)(() => ({
    ..._bexCore.queryStatus.idle,
    error: null,
    isFetching: false
  }));
  const promiseFnRef = (0, _react.useRef)(_promiseFn);
  const fetchOnce = (0, _react.useCallback)((0, _once.default)(async () => {
    let newStatus;
    try {
      setStatus({
        ..._bexCore.queryStatus.loading,
        error: null,
        isFetching: true
      });
      const data = await promiseFnRef.current();
      newStatus = {
        ..._bexCore.queryStatus.success,
        error: null,
        isFetching: false,
        data
      };
      setStatus(newStatus);
    } catch (err) {
      onError == null || onError({
        err,
        isOnline: true
      });
      errorMonitor.captureException(err);
      newStatus = {
        ..._bexCore.queryStatus.error,
        error: err,
        isFetching: false
      };
      setStatus(newStatus);
    }
    return newStatus;
  }), []);
  return {
    fetchOnce,
    status,
    promiseFnRef
  };
}
//# sourceMappingURL=usePromiseState.js.map