import { useContext, useState, useRef, useEffect } from "react";
import get_1 from "../../../../../../../lodash@4.17.21/node_modules/lodash/get.js";
import { isString, isArray } from "../../_util/is.js";
import { FormContext } from "../context.js";
import warning from "../../_util/warning.js";
var __read = globalThis && globalThis.__read || function(o, n) {
  var m = typeof Symbol === "function" && o[Symbol.iterator];
  if (!m)
    return o;
  var i = m.call(o), r, ar = [], e;
  try {
    while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
      ar.push(r.value);
  } catch (error) {
    e = { error };
  } finally {
    try {
      if (r && !r.done && (m = i["return"]))
        m.call(i);
    } finally {
      if (e)
        throw e.error;
    }
  }
  return ar;
};
var useWatch = function(field, form) {
  var formCtx = useContext(FormContext);
  var formInstance = form || formCtx.store;
  var _a = __read(useState(function() {
    var fieldValues = formInstance === null || formInstance === void 0 ? void 0 : formInstance.getFieldsValue([].concat(field));
    if (isString(field)) {
      return get_1(fieldValues, field);
    }
    return fieldValues;
  }), 2), value = _a[0], setValue = _a[1];
  var fieldRef = useRef(field);
  fieldRef.current = field;
  var valueRef = useRef(JSON.stringify(value));
  useEffect(function() {
    if (!formInstance) {
      warning(true, "formInstance is not available");
      return;
    }
    var registerWatcher = (formInstance === null || formInstance === void 0 ? void 0 : formInstance.getInnerMethods(true)).registerWatcher;
    var updateValue = function() {
      var field2 = fieldRef.current;
      var formValues = formInstance.getFieldsValue([].concat(field2));
      var newValue = formValues;
      if (!isArray(field2)) {
        newValue = get_1(formValues, field2);
      }
      var newValueString = JSON.stringify(newValue);
      if (valueRef.current !== newValueString) {
        setValue(newValue);
        valueRef.current = newValueString;
      }
    };
    updateValue();
    var cancelWatch = registerWatcher && registerWatcher(updateValue);
    return function() {
      cancelWatch && cancelWatch();
    };
  }, []);
  return value;
};
const useWatch$1 = useWatch;
export {
  useWatch$1 as default
};
//# sourceMappingURL=useWatch.js.map
