I’m building a simple Facebook clone with React and Firebase and this is what the users collection looks like:
Users can store their friends by their user document ID. I am setting these friends in a friends variable when the user logs in:
const [friends, setFriends] = useState([]);
useEffect(() => {
setFriends(userInfo[0]?.data.friends);
})
My question is, how can I loop through the users and display only users that are in the friends array? Here is the code I have that isn’t working because it’s not checking any particular value in the friends array:
<Row>
{users.map(user => (
user.id == friends ?
(
<Col>
<div
id={user.id}
key={user.id}
>
<h3
>
{user.data.name}
</h3>
<Link>
<button
>
View Profile
</button>
</Link>
</div>
</Col>
) : null
))}
</Row>
2
Answers
"friends" is an array which contains a list of user id. So in this case, you compare user.id to an array (friends) so it cannot work.
Instead, you should change the statement to: users.map( user => friends.includes(user.id) ? … : …), so if the user.id in the friends array, it will return what you expect.
By the way, you should add userInto as a dependency to your useEffect, ex:
useEffect( () => {…},[userInfo]), so the state will only be updated when the userInfo data changes.
Correct Code: