Problem fetching data from inner join table with axios in react

Viewed 703

I'm new in react so I'm trying to put the returning data from express with axios in fields, but i have some problems do display data from the join table.

import React, { Component } from "react";
import FilmesDataService from "../services/filmes.service";

export default class Tutorial extends Component {
    constructor(props) {
        super(props);
        this.onChangeTitle = this.onChangeTitle.bind(this);
        this.onChangeDescription = this.onChangeDescription.bind(this);
        this.onChangeFoto = this.onChangeFoto.bind(this);
        this.onChangeGenero = this.onChangeGenero.bind(this);
        this.getTutorial = this.getTutorial.bind(this);
        this.updateTutorial = this.updateTutorial.bind(this);
        this.deleteTutorial = this.deleteTutorial.bind(this);

        this.state = {
            dataProduto: {},
            message: ""
        };
    }

    componentDidMount() {
        this.getTutorial(this.props.match.params.id);
    }

    onChangeTitle(e) {
        const titulo = e.target.value;

        this.setState(function(prevState) {
            return {
                dataProduto: {
                    ...prevState.dataProduto,
                    titulo: titulo
                }
            };
        });
    }

    onChangeDescription(e) {
        const descricao = e.target.value;

        this.setState(prevState => ({
            dataProduto: {
                ...prevState.dataProduto,
                descricao: descricao
            }
        }));
    }

    onChangeFoto(e) {
        const foto = e.target.value;

        this.setState(prevState => ({
            dataProduto: {
                ...prevState.dataProduto,
                foto: foto
            }
        }));
    }

    onChangeGenero(e) {
        const generoId = e.target.value;

        this.setState(prevState => ({
            dataProduto: {
                ...prevState.dataProduto,
                generoId: generoId
            }
        }));
    }

    getTutorial(id) {
        FilmesDataService.get(id)
            .then(response => {
                this.setState({
                    dataProduto: response.data
                });
                console.log(response.data);
            })
            .catch(e => {
                alert(e);
            });
    }

    updateTutorial() {
        FilmesDataService.update(this.state.dataProduto.id, this.state.dataProduto)
            .then(response => {
                console.log(response.data);
                this.setState({
                    message: "Alterado com Sucesso!"
                });
            })
            .catch(e => {
                console.log(e);
            });
    }

    deleteTutorial() {
        FilmesDataService.delete(this.state.dataProduto.id)
            .then(response => {
                console.log(response.data);
                this.props.history.push("/user");
            })
            .catch(e => {
                console.log(e);
            });
    }

    render() {
        const { dataProduto } = this.state;

        return (
            <div>
                <div className="edit-form">
                    <h4>Tutorial</h4>
                    <form>
                        <div className="form-group">
                            <label htmlFor="title">Title</label>
                            <input
                                type="text"
                                className="form-control"
                                value={dataProduto.titulo}
                                onChange={this.onChangeTitle}
                            />
                        </div>
                        <div className="form-group">
                            <label htmlFor="description">Description</label>
                            <input
                                type="text"
                                className="form-control"
                                value={dataProduto.descricao}
                                onChange={this.onChangeDescription}
                            />
                        </div>

                        <div className="form-group">
                            <label htmlFor="description">Foto</label>
                            <input
                                type="text"
                                className="form-control"
                                value={dataProduto.foto}
                                onChange={this.onChangeFoto}
                            />
                        </div>

                        <div class="form-group">
                            <label for="inputState">Género</label>
                            <select id="inputState" class="form-control" onChange={this.onChangeGenero}>
                                <option selected value={dataProduto.generoId}>
                                    {dataProduto.genero.name}
                                </option>
                                <option value="1">Drama</option>
                                <option value="2">Comédia</option>
                            </select>
                        </div>
                    </form>

                    <button className="badge badge-danger mr-2" onClick={this.deleteTutorial}>
                        Delete
                    </button>

                    <button type="submit" className="badge badge-success" onClick={this.updateTutorial}>
                        Update
                    </button>
                    <p>{this.state.message}</p>
                </div>
            </div>
        );
    }
}

filmes.service.js

import axios from "axios";
import authHeader from "./auth-header";

const API_URL = "http://localhost:8080/api/";

class FilmesDataService {
    getAll() {
        // return axios.get("/trabalho");
        return axios.get(API_URL + "filmes/list", { headers: authHeader() });
    }

    get(id) {
        return axios.get(API_URL + `filmes/single/${id}`, { headers: authHeader() });
    }
}

export default new FilmesDataService();

filmes.routes

const { authJwt } = require("../middlewares");
const filmes = require("../controllers/filmes.controller.js");
const controller = require("../controllers/user.controller");

module.exports = app => {
    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Headers", "x-access-token, Origin, Content-Type, Accept");
        next();
    });

    app.post("/api/filmes/create", [authJwt.verifyToken, authJwt.isAdmin], filmes.create);

    app.get("/api/filmes/list", filmes.findAll);

    app.get("/api/filmes/single/:id", filmes.findOne);
};

filmes.controller.js

exports.findOne = (req, res) => {
    const id = req.params.id;

    Filmes.findByPk(id, { include: [Generos] })
        .then(data => {
            res.send(data);
        })
        .catch(err => {
            res.status(500).send({
                message: "Ocorreu um erro a retirar os dados do produto com id=" + id
            });
        });
};

I just want put the value name of generos table on that field: enter image description here

but when i try tu i got this error: enter image description here

2 Answers

You're trying to display dataProduto.genero which is an object and therefore not qualified to be rendered this way:

<option selected value={dataProduto.generoId}>{dataProduto.genero}</option>

You should do

<option selected value={dataProduto.generoId}>{dataProduto.genero.name}</option>

I think it's wrong. You are using an object in Option child, so it's not valid as React Child. Alternative, you should change to:

<option selected value={dataProduto.genero.id}>{dataProduto.genero['id' or 'name']}</option>

It's should work.

Related