Problem with dynamic table in react

0

I am new to react and I am creating my first crud application with Mysql / react / express js.

My problem is that I can not render the body of the table because the data that I am receiving apparently I am not storing it well.

The data I get from an sql query, and I create the body of the table using the map function, the error I get is that map is not a function.

Thank you very much in advance

Table.js

function SimpleTable(props) {


  return (
    <Paper className={props.root}>
      <Table className={props.table}>
        <TableHead>
          <TableRow>
            <TableCell>Familia</TableCell>
            <TableCell numeric>Genero</TableCell>
            <TableCell numeric>Especie </TableCell>
            <TableCell numeric>Calidad </TableCell>
            <TableCell numeric>Tamaño </TableCell>
            <TableCell numeric>Pais </TableCell>
            <TableCell numeric>Comentario </TableCell>
            <TableCell numeric>Precio </TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {props.datos.map(molusco => {
            return (
              <TableRow >
                <TableCell component="th" scope="row">
                  {molusco.familia}
                </TableCell>
                <TableCell numeric>{molusco.genero}</TableCell>
                <TableCell numeric>{molusco.especie}</TableCell>
                <TableCell numeric>{molusco.calidad}</TableCell>
                <TableCell numeric>{molusco.tamaño}</TableCell>
                <TableCell numeric>{molusco.pais}</TableCell>
                <TableCell numeric>{molusco.comentario}</TableCell>
                <TableCell numeric>{molusco.precio}</TableCell>
              </TableRow>
            );
          })}
        </TableBody>
      </Table>
    </Paper>
  );
}

SimpleTable.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(SimpleTable);

App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import SideBar from './sideBar'
import Table from './table'

class App extends Component {
  render() {
    return (
      <SideBar> 
        <Table datos={rows}/> 
      </SideBar> 



    );
  }
}

export default App;

var rows= fetch('/express')
  .then(function(response) {
    console.log(response)
    return response;
  })
  .then(function(myJson) {
    console.log(myJson);
  });

  console.debug(rows)
  console.log(rows)

Server.js

const express = require('express');
const app = express();
var mysql      = require('mysql');
const port = process.env.PORT || 5000;

var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'shells'
});
connection.connect(); 


// console.log that your server is up and running
app.listen(port, () => console.log('Listening on port ${port}'));

// create a GET route
app.get('/express', (req, res) => {
  // res.send({ saludo: 'YOUR EXPRESS BACKEND IS CONNECTED TO REACT' });
  connection.query('select * from shell', function(err, rows, fields) {

    res.send(JSON.stringify(rows));
  });




});
    
asked by Javier Richards 02.10.2018 в 22:14
source

1 answer

0

The problem is that you are doing the fetch out of the React component so you do not record it, you are not converting the answer to json, for those two reasons at the time of rendering your variable rows is undefined o Maybe it's a pending promise.

The solution I propose is to use the lifecycle componentDidMount that is executed once the components are mounted in the DOM.

// App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import SideBar from './sideBar'
import Table from './table'

class App extends Component {
  // Agregamos este código
  constructor(props) {
      super(props);
      this.state = {
          rows: [] // Lo declaramos como un array para que al momento del render no vaya a dar problemas de undefined o que map no es una función
      }
  }
  componentDidMount() {
      fetch('/express')
      .then(function(response) {
       console.log(response)
       return response.json(); // Utilizamos la función json para poder consumir los datos.
     })
      .then(function(myJson) {
       console.log(myJson);
       this.setState({ rows: myJson });
     });
  }

  render() {
    const { rows } = this.state; // Declaramos la variable rows
    return (
      <SideBar> 
        <Table datos={rows}/> 
      </SideBar>
    );
  }
}

export default App;
    
answered by 29.10.2018 в 19:02