"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _native = require("@react-navigation/native");
var _react = require("react");
function useLiveObject({
  fetcher,
  params,
  callback = () => {},
  options,
  enabled = true
}) {
  const [item, setItem] = (0, _react.useState)(null);
  const [isLoading, setIsLoading] = (0, _react.useState)(false);
  const [error, setError] = (0, _react.useState)(null);
  const unsubscribeRef = (0, _react.useRef)(null);
  const callbackFnRef = (0, _react.useRef)(null);
  callbackFnRef.current = response => {
    if (!enabled) return undefined;
    if (params == null) return undefined;
    setIsLoading(response.loading);
    if (response.data) setItem(response.data);
    setError(response.error);
    callback(response);
  };
  const stableCallback = (0, _react.useCallback)(response => {
    var _callbackFnRef$curren;
    (_callbackFnRef$curren = callbackFnRef.current) === null || _callbackFnRef$curren === void 0 || _callbackFnRef$curren.call(callbackFnRef, response);
  }, []);
  (0, _native.useFocusEffect)((0, _react.useCallback)(() => {
    if (!enabled) return undefined;
    const {
      unsubscribe
    } = subscribe({
      fetcher,
      params,
      callback: stableCallback,
      options
    });
    return () => unsubscribe();
  }, [JSON.stringify(params), enabled]));
  const refresh = () => {
    if (unsubscribeRef.current) unsubscribeRef.current();
    const {
      unsubscribe
    } = subscribe({
      fetcher,
      params,
      callback: stableCallback,
      options
    });
    unsubscribeRef.current = unsubscribe;
    return () => unsubscribe();
  };
  return {
    item,
    isLoading,
    error,
    refresh
  };
}
var _default = exports.default = useLiveObject;
const subscribe = ({
  fetcher,
  params,
  callback,
  options
}) => {
  const unsubscribe = fetcher(params, response => callback(response), options);
  return {
    unsubscribe
  };
};
//# sourceMappingURL=useLiveObject.js.map