I have some functions which handle a user following and unfollowing another user.
const handleFollowUser = async () => {
try {
const { data } = await followUser({
variables: {
followedByUserId: Number(state.currentUser.id),
followingUserId: Number(postFromUser.id)
}
})
if (data) {
refetchFollowers()
checkIsFollowing()
}
} catch (err) {
console.log(err)
}
}
const handleUnfollowUser = async () => {
try {
const { data } = await unfollowUser({
variables: {
userId: Number(state.currentUser.id),
userIdToUnfollow: Number(postFromUser.id)
}
})
if (data) {
refetchFollowers()
checkIsFollowing()
}
} catch (err) {
console.log(err)
}
}
checkIsFollowing searches a users followers list and checks if the current user ID in there. This always works properly on page load.
const checkIsFollowing = () => {
followersData?.getAllUserFollowers.some((follower) => {
setIsFollowing(follower.id === state.currentUser.id)
})
}
useEffect(() => {
if (followersData) {
checkIsFollowing()
}
}, [followersData])
The problem im having is when I unfollow a user the boolean isFollowing is not flipping back to false. It flips properly when I follow the user initially but not if I unfollow them. Even though followersData?.getAllUserFollowers shows an empty array after refetchFollowers runs
Let's wrap the two async method within useCallback of react, remove the checkIsFollowing() call from within these two async as it is being called from useEffect, and adding dependency to these methods:
const handleFollowUser = useCallback(async () => {
try {
const { data } = await followUser({
variables: {
followedByUserId: Number(state.currentUser.id),
followingUserId: Number(postFromUser.id)
}
})
if (data) {
//When you receive data, you should set followersData state here. Like, setFollowersData(data). Please, make sure that you have done it properly.
refetchFollowers()
}
} catch (err) {
console.log(err)
}
},[state.currentUser.id, postFromUser.id])
const handleUnfollowUser = useCallback(async () => {
try {
const { data } = await unfollowUser({
variables: {
userId: Number(state.currentUser.id),
userIdToUnfollow: Number(postFromUser.id)
}
})
if (data) {
refetchFollowers()
}
} catch (err) {
console.log(err)
}
}, [state.currentUser.id, postFromUser.id])
After that, let's modify the dependency of useEffect:
useEffect(() => {
if (followersData) {
checkIsFollowing()
}
}, [followersData, handleFollowUser, handleUnfollowUser])
And, as pilchard said in his comment, you should concentrate on your checkIsFollowing method if it returns correctly.