skip to Main Content

I’m building a simple Facebook clone with React and Firebase and this is what the users collection looks like:

firebase users collection

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


  1. "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.

    Login or Signup to reply.
  2. Correct Code:

    users.map ((user,index)=>{
    if (friends && friends.includes(user.id)){
    //then do what you want on true condition 
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search