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

210
Visualizações
Pushing API-data to nested array and render results

I'm calling an API to get an array of users, sort them, and put them in an array if the personalTrainerId is equal to my userId, and then render them into cards.

I'd like to receive the data as

MyClients: [{'userId':86,'firstName':'Client','lastName':'23','email':'newclient@ab'},{'userId':96,'firstName':'cl','lastName':'ie','email':'cl@ie'}]

But instead I get the result

MyClients: {'userId':86,'firstName':'Client','lastName':'23','email':'newclient@ab'},{'userId':96,'firstName':'cl','lastName':'ie','email':'cl@ie'},

(Without the brackets)

I get the response from the call, but when I try to render them, the object comes back as "undefined" - I'm quite new to this, and I might be approaching it all wrong. Any help would be appreciated.

My code for adding the response to an array:

function AddClients(response){
    const users = response.data;
    var newClient="";
    const myId = parseInt(getUserId())

    for(var i = 0; i < users.length; i++ ){
            if (response.data[i].personalTrainerId === myId){
                newClient=("{'userId':"+response.data[i].userId+",'firstName':'"+response.data[i].firstName+"',
'lastName':'"+response.data[i].lastName+"','email':'"+response.data[i].email+"'}")
                    //
                myClients.push(JSON.parse(JSON.stringify(newClient)))
                
        }
    }
    
    console.log("Length after this: "+ myClients.length); // returns 57 as expected
    myClients.map(RenderCard) // Calling to render
}

Then I try to render it to a card with bootstrap:

const RenderCard = (card, index) =>{ 

    return(         
            <Card border="dark" style={{ width: '18rem' }} key={index}>
            <Card.Header>Client number: {card.userId} </Card.Header>
                <Card.Body>
                    <Card.Title>Name: 
                        {card.firstName} {card.lastName}{console.log("card firstname: " + card.firstName)} 
                    </Card.Title> // Console.log returns "card firstname: undefined"
                    <Card.Text>
                        Mail: {card.email}
                    </Card.Text>
                </Card.Body>
            </Card>
        )
    
}

__

I really don't know how to get the right data in. Is there a better approach? Am I just missing something? I get no errors, and as I'm new to this I don't really know how to debug it properly.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You must add your response to a state:

const [card, setCard] = React.useState({});
function AddClients(response){
  setCard(response.data);
}

After that you can use that state to render the data. If you want to render an array you can use code like this:

return (
  <>
    {
      cards.map(card=>         
        <Card border="dark" style={{ width: '18rem' }} key={index}>
        <Card.Header>Client number: {card.userId} </Card.Header>
            <Card.Body>
                <Card.Title>Name: 
                    {card.firstName} {card.lastName}{console.log("card firstname: " + card.firstName)} 
                </Card.Title> // Console.log returns "card firstname: undefined"
                <Card.Text>
                    Mail: {card.email}
                </Card.Text>
            </Card.Body>
        </Card>
      )
    }
  </>
);

but if you have an object of card:

return (
  <>      
      <Card border="dark" style={{ width: '18rem' }} key={index}>
        <Card.Header>Client number: {card.userId} </Card.Header>
        <Card.Body>
            <Card.Title>Name: 
                    {card.firstName} {card.lastName}{console.log("card firstname: " + card.firstName)} 
                </Card.Title> // Console.log returns "card firstname: undefined"
                <Card.Text>
                    Mail: {card.email}
                </Card.Text>
            </Card.Body>
        </Card>
      )
    }
  </>
);
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