consume api rest with react and render the data in a table

1

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:

    
asked by anonymous 04.05.2018 / 15:45

1 answer

2

When you need to consume data from an API it is recommended that you make the request in the componentDidMount method, which is one of the life cycle methods of a React component. In addition, you must not call the setState () method in the constructor (and in the refresh method you call this), you method). So the first change needed in your code is to invoke the refresh () method inside componentDidMount ().

After that, to render the data that you loaded into the table, simply loop the array list and return the items inside 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>
    ) 
}
    
11.06.2018 / 16:24