@replyke/core
Version:
Replyke: Build interactive apps with social features like comments, votes, feeds, user lists, notifications, and more.
64 lines • 2.62 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = require("react");
const useFollowUser_1 = __importDefault(require("./useFollowUser"));
const useUnfollowUserByUserId_1 = __importDefault(require("./useUnfollowUserByUserId"));
const useFetchFollowStatus_1 = __importDefault(require("./useFetchFollowStatus"));
const useUser_1 = __importDefault(require("../../user/useUser"));
function useFollowManager({ userId }) {
const { user } = (0, useUser_1.default)();
const [isFollowing, setIsFollowing] = (0, react_1.useState)(null);
const [isLoading, setIsLoading] = (0, react_1.useState)(true);
const followUser = (0, useFollowUser_1.default)();
const unfollowUserByUserId = (0, useUnfollowUserByUserId_1.default)();
const fetchFollowStatus = (0, useFetchFollowStatus_1.default)();
// Keep a ref so the effect always calls the latest version without being in deps
const fetchFollowStatusRef = (0, react_1.useRef)(fetchFollowStatus);
fetchFollowStatusRef.current = fetchFollowStatus;
(0, react_1.useEffect)(() => {
const loadFollowStatus = async () => {
try {
setIsLoading(true);
const result = await fetchFollowStatusRef.current({ userId });
setIsFollowing(result.isFollowing);
}
catch (error) {
console.error("Failed to fetch follow status:", error);
setIsFollowing(false);
}
finally {
setIsLoading(false);
}
};
if (userId && user?.id && user.id !== userId) {
loadFollowStatus();
}
}, [userId, user?.id]);
const toggleFollow = (0, react_1.useCallback)(async () => {
if (isFollowing === null || isLoading || user?.id === userId)
return;
try {
if (isFollowing) {
await unfollowUserByUserId({ userId });
setIsFollowing(false);
}
else {
await followUser({ userId });
setIsFollowing(true);
}
}
catch (error) {
console.error("Failed to toggle follow status:", error);
}
}, [isFollowing, isLoading, userId, followUser, unfollowUserByUserId]);
return {
isFollowing,
isLoading,
toggleFollow,
};
}
exports.default = useFollowManager;
//# sourceMappingURL=useFollowManager.js.map