{user.anotherUser.followers &&
user.anotherUser.followers.map((a) => {
if (user.user._id === a._id) {
return console.log("following button");
} else {
return console.log("follow button");
}
})}
Data:
{
"username": "John",
"followers": [],
}
The problem is that return console.log("follow button"); does not run when the followers array is empty.
When the array is not empty, the return console.log("following button") successfully runs which is good.
When not empty, the followers array contains objects of different users (populated it on the backend to access ObjectID properties) like this:
{
"username": "John",
"followers": [
"_id": "123123123",
"username": "David"
],
}
What did I do wrong?
The user.user._id is my id which is 123123123 in this case.
EDIT:
{user.anotherUser.followers &&
user.anotherUser.followers.length > 0 ? (
user.anotherUser.followers.map((a) => {
if (user.user._id === a._id) {
return <Button>Following</Button>;
} else {
return <Button>Follow</Button>;
}
})
) : (
<Button>Follow</Button>
)}
With this, both Following and Follow buttons are displayed. Only one button should be display by logic.
EDIT2:
{user.anotherUser.followers &&
user.anotherUser.followers.length > 0 ? (
user.anotherUser.followers.map((a) => {
if (user.user._id === a._id) {
return <Button>Following</Button>;
}
})
) : (
<Button>Follow</Button>
)}
Now the Follow button does not appear if the length > 0, because someone else's id is in the array, although mine (user.user._id) is not there. The Follow button should appear if the array length > 0 and if my user.user._id is not inside it either.
EDIT3:
I could use a different approach because user.user has a following array field in the database.
let userFollowing =
user.user.following && user.user.following.map((a) => a._id);
And then display one button like this:
{user.user.following &&
userFollowing.includes(user.anotherUser._id) && (
<Button className="follow-true">Following</Button>
)}
{user.user.following &&
!userFollowing.includes(user.anotherUser._id) && (
<Button className="follow-false">Follow</Button>
)}
EDIT4: better and final solution:
Above the return()
let anotherUserFollowers =
user.anotherUser.followers &&
user.anotherUser.followers.map((a) => a._id);
In the return()
{user.anotherUser.followers &&
anotherUserFollowers.includes(user.user._id) && (
<Button
onClick={() =>
props.follow({
id: user.anotherUser._id,
})
}
className="follow-true"
>
Following
</Button>
)}
{user.anotherUser.followers &&
!anotherUserFollowers.includes(user.user._id) && (
<Button
onClick={() =>
props.follow({
id: user.anotherUser._id,
})
}
className="follow-false"
>
Follow
</Button>
)}
returnit in the conditional, and yes this is in the JSX