"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useTrendingCommunities = void 0;
var _react = require("react");
var _tsSdkReactNative = require("@amityco/ts-sdk-react-native");
var _useAuth = _interopRequireDefault(require("../../core/hooks/useAuth"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const useTrendingCommunities = () => {
  const {
    isConnected
  } = (0, _useAuth.default)();
  const [communities, setCommunities] = (0, _react.useState)();
  const [loading, setLoading] = (0, _react.useState)(true);
  const [error, setError] = (0, _react.useState)(null);
  const unsubscribersRef = (0, _react.useRef)([]);
  const fetchTrendingCommunities = () => {
    setLoading(true);
    return _tsSdkReactNative.CommunityRepository.getTrendingCommunities({
      limit: 5
    }, ({
      error,
      loading,
      data
    }) => {
      setLoading(loading);
      if (error) setError(error);
      if (!loading) {
        setCommunities(data);
      }
    });
  };
  const unsubscribeListener = () => {
    unsubscribersRef.current.forEach(unsubscriber => unsubscriber());
    unsubscribersRef.current = [];
  };
  const refresh = () => {
    unsubscribeListener();
    setError(null);
    const unsubscribe = fetchTrendingCommunities();
    unsubscribersRef.current.push(unsubscribe);
  };
  (0, _react.useEffect)(() => {
    if (!isConnected) return () => {};
    const unsubscribe = fetchTrendingCommunities();
    unsubscribersRef.current.push(unsubscribe);
    return () => unsubscribeListener();
  }, [isConnected]);
  return {
    communities,
    loading,
    error,
    refresh
  };
};
exports.useTrendingCommunities = useTrendingCommunities;
//# sourceMappingURL=useTrendingCommunities.js.map