import { useFocusEffect } from '@react-navigation/native';
import { useCallback, useRef, useState } from 'react';
function useLiveObject({
  fetcher,
  params,
  callback = () => {},
  options,
  enabled = true
}) {
  const [item, setItem] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const unsubscribeRef = useRef(null);
  const callbackFnRef = 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 = useCallback(response => {
    var _callbackFnRef$curren;
    (_callbackFnRef$curren = callbackFnRef.current) === null || _callbackFnRef$curren === void 0 || _callbackFnRef$curren.call(callbackFnRef, response);
  }, []);
  useFocusEffect(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
  };
}
export default useLiveObject;
const subscribe = ({
  fetcher,
  params,
  callback,
  options
}) => {
  const unsubscribe = fetcher(params, response => callback(response), options);
  return {
    unsubscribe
  };
};
//# sourceMappingURL=useLiveObject.js.map