consume Rest api with React and render the data in a table

Asked

Viewed 7,851 times

2

my code:

import React, { Component } from 'react'
import axios from 'axios'

import PageHeader from '../template/pageHeader'
import cadastroForm from './cadastroForm'
import cadastroList from './cadastroList'

const URL = 'http://localhost:3003/api/cadastros'

export default class Cadastro extends Component {
    constructor(props) {
        super(props);
        this.state = { listaItens: [] }
        this.refresh()

   }

    refresh(Nome = '') {
        const search = Nome ? `&Nome__regex=/${Nome}/` : ''
        axios.get(`${URL}?sort=-createdAt${search}`)
        .then(response => { this.setState({ listaItens: response.data}); })
        .catch(() => { console.log('Erro ao recuperar os dados'); });    
    }

     render() {
       return (

     <div>

     {this.state.listaItens.map(function(item)  {console.log(item)})}

      </div>
        ) 
    }


}

returns:

inserir a descrição da imagem aqui

1 answer

4


When you need to consume data from an API it is recommended to request in the method componentDidMount, which is one of the life cycle methods of an React component. Also, you should not call the setState() method in the constructor (and in the refresh method you call this method). Thus, the first necessary change in your code is to invoke the refresh() method within componentDidMount().

After that, to render the data you’ve uploaded into the table just loop the listItens array and return the items within a table structure.

Your code will look like this after the changes:

export default class Cadastro extends Component {
constructor(props) {
    super(props);
    this.state = { listaItens: [] }

    this.refresh = this.refresh.bind(this);
}

refresh(Nome = '') {
    const search = Nome ? `&Nome__regex=/${Nome}/` : ''
    axios.get(`${URL}?sort=-createdAt${search}`)
    .then(response => { this.setState({ listaItens: response.data}); })
    .catch(() => { console.log('Erro ao recuperar os dados'); });    
}

componentDidMount() {
    this.refresh()
}

render() {
    return (

        <div>
            <table>

                <tr>
                    <th scope="col">Nome</th>
                    <th scope="col">CPF/CNPJ</th>
                </tr>

               {this.state.listaItens.map(function(item)  
                  {
                     return (
                         <tr>
                             <td>{item.Nome}</td>
                             <td>{item.CpfCnpj}</td>
                         </tr>
                     )
                  }
               }

            </table>
        </div>
    ) 
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.