I am learning React and I have successfully mapped the post titles to a div on the page. I also need to take the "userid" from the posts and get the user's name from the users state and add it to a
on the div. I can send the userid to a function which is set to return the corresponding user but it does not show up on the page. I would appreciate a review of my code to see where I am going wrong. I can log out to the console the right user but it doesn't show up on the HTML. The second
in the section is the one that is not populating I would need to do that on comments as well later on so for now I just assigned a static innerHTML for that. here is my code that I have. Thanks in advance.
export default function Posts(name) {
const [posts, setPosts] = useState([]);
const [comments, setComments] = useState([]);
const [users, setUsers] = useState([])
// get Posts
useEffect(() => {
getPosts()
.then(items => {
setPosts(items)
})
// Get all Users
getUsers()
.then(users => {
setUsers(users)
})
// Get all comments
getComments()
.then(comments =>{
setComments(comments)
})
}, [])
// get individual user by userId
const getPostAuthor = (userid)=> {
users.filter((item) =>{
if ( item.id === userid){
console.log(item.name)
return item.name
}
})
}
return ( <PostsSection> {
posts.map(item => <Post><PostTitle key ={ item.title }> { item.title } </PostTitle><PostBody key={item.body}>{item.body}</PostBody><PostFooter><p>comments:4</p><p>{getPostAuthor(item.userId)}</p></PostFooter></Post>)}
</PostsSection> )
}
users.filter is returning item.name, but getPostAuthor() does not return anything. You could put a return before your users.filter function but since Array.filter() returns an array and you want one user I'd expect that is not what you want. You could instead try Array.find