Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
Matching post author to post in React from state

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> )
        }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!