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

354
Visualizações
Trying to Print Data from Get Request via Axios

I'm trying to print off SQL data from a get request using axios. I'm using express server-side, and my front end is React. Within my react component, I have a function that has the axios GET call, and then I call that said function within the render. I can get the data fine. My issue is actually printing the data to the table. Here is my code so far:

  getTableData(){
      axios.get("/api")
      .then(function (response){
        return(
          Object.keys(response).map( (row, index) => (
              <TableRow key={index} selected="false">
                <TableRowColumn>Test</TableRowColumn>
                <TableRowColumn>Test</TableRowColumn>
              </TableRow>
          ))
        )
      })
      .catch(function (error){
          console.log(error);
      })
  }

This is the function I use to do the API call, as well as try to print the table. I call it within the render function as {this.getTabledata()}.

Here is the the get request within my server.js:

app.get('/api', function (req, res){
    sql.connect(config, err =>{
        new sql.Request().query('select * from Counselling', (err, result) =>{
            var table = new Object();
            result["recordset"].map( (row, index) => (
                table[row["StudentName"]] = row["StudentNumber"]
            ));
            res.send(table);
            sql.close();
        });
    });

Is there something I'm missing? Do I have to use a specific mapping function for the rows?

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

0

First of all don't make the api call directly from render method, do that either in componentDidMount lifecycle method or on any specific event. Store the response in state variable because api call will be a asynchronous call, it will not return the ui elements.

Use this to fetch the data from server:

componentDidMount(){
    axios.get("/api")
        .then( (response) => {
            this.setState({response: response})
        })
        .catch( (error) => {
            console.log(error);
        })
}

Use this method, it will return the Table rows once you get the response from server, because when we do setState, React render the component again.

getTableData(){

    if(!this.state.response) return null;  //added this line

    return Object.keys(this.state.response).map( (row, index) => (
         <TableRow key={index} selected="false">
             <TableRowColumn>Test</TableRowColumn>
             <TableRowColumn>Test</TableRowColumn>
         </TableRow>
    ))     
}
about 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