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

145
Visualizações
How to get object data and push an array in React?

I have an endpoint that returns an object. The object is:

{
"id": "669f8",
"creation_date": "2022-01-13 10:33:06.046652+01:00",
"case_type": "Summary",
"process_types": "",
"case_id": "ad23423s",
"current_stage": "",
"current_stage_name": "",
"consolidation": "None",
"last_change_date": "2022-01-14 14:35:17.563449+01:00",
"status": 1,
"assign": "Yes"

} I want to display it in my React project. Firstly I want to take object fields, and then the values.

I wrote this code:

class DetailsPage extends React.Component<DetailProps> {
  async getData() {
    const data = await Dependencies.backend.getList(this.props.url);
    if (data) {
      return data;
    }
    return [];
  }
  render() {
    const data = this.getData()
    const fields: string[][] = []
    const test: any[] = []
    data.then((val: any) =>
      fields.push(Object.keys(val))
      // console.log(val)
    )  .catch(err => console.log("There was an error:" + err))
    console.log("testeststt")
    console.log(fields)

    return (
      <div>
        <h1>Hoi!</h1>
      </div>
    );
  }
}

The console.log(fields) returns []

And when I open the array it shows

output

But I can't get the 0th row.

How can I get and push another array or something?

almost 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The reason for this is that the render function only renders out the UI. It is not supposed to make asynchronous stuff. Since, you need to invoke the API call when the component mounts, you can do it in componentDidMount and when you have data, update it in state.

This way, on the initial render, you will have 0 items in the data. When you update the state, it will re-render the component and then you will have items in your data.

You can do something like the following:

componentDidMount() {
  this.getData()
}

async getData() {
  const data = await Dependencies.backend.getList(this.props.url);
  this.setState({ data: data ?? [] })
}

render() {
  const { data } = this.state;
  console.log(data)
}
almost 4 years ago · Santiago Trujillo 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