Search code examples
javascriptreactjsmdbreact

Adding to object that contains an array an object in state in React


Hello I am building an app that renders a table that receives data from an API.

I am using for the table MDBReact and I am having a hard time adding rows to the table.

In this.state I have an object datatable that contains an array names rows and I would like to add objects to this array.

This is the code and what I have tried but it does not work.

The problem is in the this.setState, how should I write the adding of an object to an array contained in the datatable object. Thanks

import React, { useState } from 'react';
import { MDBDataTableV5 } from 'mdbreact';
import axios from 'axios';






class ListaMesaje extends React.Component {

componentDidMount() {
axios.get(`http://localhost/spv/react-php/src/server.php`)
.then(res => {
  const persons = res.data;

  for(var i = 0; i < 3; i++) {
   
  this.setState({datatable:{...this.state.datatable,rows:persons.mesaje[i]}})
    
    
    
  }

})

}

constructor(props){
super(props);
this.state = {
datatable: {
  columns: [
    {
      label: 'CIF',
      field: 'cif',
      width: 150,
      attributes: {
        'aria-controls': 'DataTable',
        'aria-label': 'Name',
      },
    },
    {
      label: 'Data creare',
      field: 'data_creare',
      width: 270,
    },
    {
      label: 'ID Solicitare',
      field: 'id_solicitare',
      width: 200,
    },
    {
      label: 'Tip',
      field: 'tip',
      sort: 'asc',
      width: 100,
    },
    {
      label: 'ID',
      field: 'id',
      sort: 'disabled',
      width: 150,
    },
    {
      label: 'Detalii',
      field: 'detalii',
      sort: 'disabled',
      width: 100,
    },
  ],
  
  rows: [
    
 
  ],
}
}
}

render() {
return(
<div>
<MDBDataTableV5 hover entriesOptions={[5, 20, 25]} entries={5} pagesAmount={4} data= 
{this.state.datatable} fullPagination />
</div>
);
}

}

export default ListaMesaje;

Solution

  • You should do simply replace

      for(var i = 0; i < 3; i++) { 
      this.setState({datatable:{...this.state.datatable,rows:persons.mesaje[i]}})
      }
    

    to

     this.setState({datatable:{...this.state.datatable,rows:[...persons.mesaje]}})