@replyke/core
Version:
Replyke: Build interactive apps with social features like comments, votes, feeds, user lists, notifications, and more.
59 lines • 2.21 kB
JavaScript
import { useState, useEffect, useCallback, useRef } from "react";
import useFollowUser from "./useFollowUser";
import useUnfollowUserByUserId from "./useUnfollowUserByUserId";
import useFetchFollowStatus from "./useFetchFollowStatus";
import useUser from "../../user/useUser";
function useFollowManager({ userId }) {
const { user } = useUser();
const [isFollowing, setIsFollowing] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const followUser = useFollowUser();
const unfollowUserByUserId = useUnfollowUserByUserId();
const fetchFollowStatus = useFetchFollowStatus();
// Keep a ref so the effect always calls the latest version without being in deps
const fetchFollowStatusRef = useRef(fetchFollowStatus);
fetchFollowStatusRef.current = fetchFollowStatus;
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 = 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,
};
}
export default useFollowManager;
//# sourceMappingURL=useFollowManager.js.map