Search code examples
reactjsmapping

how do I connect a user to post in React?


how do I connect a user to their post? the post has the user-id from who posted a review but how do I go about mapping the posts?

this is my post map

{post.map(post => (
                    <Post key={post.id} post={post} />
                ))}

fname and address are from user, post is from the list of posts and post file:

{fname}
{address}
{post}

so I have the list of posts and the lists of users, they are separate but the post has the user id of who posted it but how do I connect them? mapping through the post and when the userid from the user is equivalent to the userid from the post filter it or something? how do I connect them through that relationship?

something I'm going for but it gives an error user.post is undefined

 {post.map(post => (
                <Post
                    key={post.id}
                    food={post}
                    user={user.filter(
                        user => 
                        user.post.userid)}
                />
            ))}

Solution

  • When I set the value for the user in the post tag as below, it worked for me.

        <Post
            key={post.id}
            food={post}
            user={users.find(
                user => 
                post.userid === user.id //if you have an users array here you should use find instead of filter and then try to match the post.userid with user.id.
            )}
        />