Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

133
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda