List to frontend values of multiple tables

Asked

Viewed 83 times

-2

Good afternoon, I am a beginner in Act and Noode.js and I have a problem.

I have a table on a web page where you’ll receive the data from a trip. The columns (Id localities, name, date, time) are present in the requested model_trip, but the "name localities" column was intended to list the localities' names via id. The id of this locality is in the "Id localities" column, however when listing it gives me the error: "Typeerror: Cannot read Property 'designation' of Undefined".

For a better understanding of the table, in the first row of data, 1 is the departure id and 124 is arrival id. Enclose table photo as well as controller and models. inserir a descrição da imagem aqui

the insertion of the data in the table is done in the function loadFillData() present in this code:

import React from 'react';
import '../../../assets/css/Pagamentos.css'
import 'js-datepicker/dist/datepicker.min.css';
import '../../../assets/css/bootstrap.css';
import axios from 'axios';
import { data } from 'jquery';
const datepicker = require('js-datepicker');

class Pagina extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            pag_pendentes: []
        }
    }

    componentDidMount() {
        const picker = datepicker('#calendario', {
            formatter: (input, date, instance) => {
                input.value = new Intl.DateTimeFormat('en-GB').format(date)
            }
        });

        const url = "http://localhost:3001/operadora/pendente";
        axios.get(url)
        .then(res=>{
            if(res.data.success){
                const data = res.data.data;
                this.setState({pag_pendentes:data});
            }else{
                alert("Erro");
            }
        })
        .catch(error=>{
            alert(error)
        });
    }

    render() {
        return (
            <div>
                <div id="div-filtragem">
                    <label className="Label_DatePicker">Data inicio:</label>
                    <input placeholder="Selecione uma data" type="text" id="calendario" className="form-control DatePicker datepicker" style={{ width: "auto" }} />
                    <label className="Label_DatePicker">Data fim:</label>
                    <input placeholder="Selecione uma data" type="text" id="calendario" className="form-control DatePicker datepicker" style={{ width: "auto" }} />
                    <button type="button" className="ButtonFilter ">Filtrar</button>
                </div>
                <div className="div_tabela">

                    <table className="table tabela" >
                        <thead>
                            <tr>
                                <th scope="col">IDs localidades</th>
                                <th scope ="col">nome localidades</th>
                                <th scope="col">Nome</th>
                                <th scope="col">Data</th>
                                <th scope="col">Hora</th>
                                <th scope="col">Valor</th>
                            </tr>
                        </thead>
                        <tbody>
                            
                            {this.loadFillData()}
                        </tbody>
                    </table>
                </div>
            </div>
        );
    }
    loadFillData(){
        console.log(this.state.pag_pendentes);
        return this.state.pag_pendentes.map((data, index) => {
            
            return (
                <tr key ={index}>
                    <td className="td_viagem">{data.partida + "-"+data.chegada}</td>
                    <td>{data.pp.designacao + "-"+data.pc.designacao}</td>
                    <td>{data.pessoa.p_nome + " " +data.pessoa.u_nome}</td>
                    <td>{data.data_viagem}</td>
                    <td>{data.hora_viagem}</td>
                    <td>10€</td>
                </tr>

            )
        });
    }
}

export default Pagina;

The controller of this page is this:

var Viagem = require('../../model/viagem');
var Pedido_viagem = require('../../model/pedido_viagem');
var Estado = require('../../model/estado');
var Pessoa = require('../../model/pessoa');
var Partida = require('../../model/freguesias');
var Chegada = require('../../model/freguesias');
const sequelize = require('../../model/database');

const op_pagamentos = {}
sequelize.sync()
op_pagamentos.pendentes = async(req,res) => {
    const data = await Pedido_viagem.findAll({
        include: [Viagem],
        include: [Estado], 
        include:[{
                model: Partida,
                as:'pp',
                attributes:['designacao']
            },
            {model: Chegada, 
                as:'pc',
                attributes:['designacao']}],
        include: [{
            model: Pessoa,
            attributes:['p_nome', 'u_nome']}],
        where:{ 
            estado : "3",
        },
            order :[[ 'id', 'asc' ]],

    })
    .then(function (data) {
        return data;
    })
    .catch(error => {
        console.log('Erro: ' + error);
        return error;
    });
    res.json({success: true, data: data});

}

module.exports = op_pagamentos;

model pedido_trip:

var Sequelize = require('sequelize');
var sequelize = require('./database');
var Municipe = require('./pessoa');
var Estado  = require('./estado_pedido');
var Partida  = require('./freguesias');
var Chegada  = require('./freguesias');


var pedido_viagem = sequelize.define('pedido_viagem',{
    id:{
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true,
    },
    municipe:{
        type: Sequelize.INTEGER,
        references:{
            model:Municipe,
            key:'id'
        },
        allowNull:false  // coloca variável NOT NULL
    },

    partida:{
        type: Sequelize.INTEGER,
        references:{
            model:Partida,
            key:'id'
        },
        allowNull:false  // coloca variável NOT NULL
    },
    chegada:{
        type: Sequelize.INTEGER,
        references:{
            model:Chegada,
            key:'id'
        },
        allowNull:false  // coloca variável NOT NULL
    },
    data_viagem: {
        type:Sequelize.DATE,
        allowNull:false  // coloca variável NOT NULL
    },
    hora_viagem:{
        type:Sequelize.TIME,
        allowNull:false  // coloca variável NOT NULL
    },
    aceita_partilha:{
        type:Sequelize.INTEGER,
        allowNull:false  // coloca variável NOT NULL
    },
    necessidades_especiais: {
        type:Sequelize.INTEGER,
        allowNull:false  // coloca variável NOT NULL
    },
    bagagem: {
        type:Sequelize.INTEGER,
        allowNull:false  // coloca variável NOT NULL
    },
    estado:{
        type:Sequelize.INTEGER,
        references:{
            model: Estado,
            key:'id'
        }
    }
},
{
    timestamps: false,
    freezeTableName: true
});

pedido_viagem.belongsTo(Municipe,{foreignKey:'municipe'});
pedido_viagem.belongsTo(Partida,{as:'pp',foreignKey:'partida'});
pedido_viagem.belongsTo(Chegada,{as:'pc',foreignKey:'chegada'});

module.exports= pedido_viagem;

model parishes:

var Sequelize = require('sequelize');
var sequelize = require('./database');
var tipo_freguesia = require('./tipo_frequesia');;

var freguesia = sequelize.define('freguesias',{
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    designacao: {
         type:Sequelize.CHAR(50),
         allowNull:false  // coloca variável NOT NULL
    },   
    localizacao: {
        type: Sequelize.CHAR(100),
        allowNull:false // coloca variável NOT NULL
    },
    zona: {
        type:Sequelize.INTEGER,
        allowNull:false  // coloca variável NOT NULL
    },
    tipo_freguesia:{
        type: Sequelize.INTEGER,
        regerences:{
            model:tipo_freguesia,
            key:'id'
        },
        allowNull:false  // coloca variável NOT NULL
    }
},
{
 timestamps: false,
 freezeTableName: true,
});

module.exports = freguesia;

Please, I really appreciate if someone can help me. I’m a beginner and I don’t understand why you’re making this mistake.

Regards to all

2 answers

0

He’s basically saying that there is no data.pc, the best way to check this is to give a console.log on that date to see what’s coming back.

  • The console.log shows all values present in the requested model_trip and shows the name of the person, but does not show anything of the parish model. That is, it shows neither the departure nor the arrival, which was what I intended

0

Pq Voce does not take the: "pp" and the: "pc" and calls directly date.Partida.designation and date.Chegada.designation

  • I think it would be the same thing to do with as:"pp" and as:"pc". Also, it makes a mistake in the same

  • I think it would be interesting to put the model code too

  • I’ve already edited and put. First of all, thank you for helping me

  • These Imports are plural: var Departure = require('../../model/parishes'); var Arrival = require('../../model/parishes'); And Exports is singular: module.Exports;

  • is not like that. the model is "freguesias.js". In the controller, when placing the include : [ model: partida] and the arrival on top of the include: [model: Pessoa], shows matches and arrivals but no longer shows the name of the person... gives the same error but in this case for p_name

  • Neither is that. even with this require gives error.

  • Already tried to put a separate include for Departure and Arrival

  • It’s not that either. I don’t think it has anything to do with the include code. By reversing the order of the person includes and departure, I can show the departure and arrival but no longer shows the name of the person

Show 3 more comments

Browser other questions tagged

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