React-chartjs-2 charts do not load on screen

1

import React, { Component } from 'react';
import {Bar} from 'react-chartjs-2';
import $ from 'jquery';

//NÚMERO DE VIAGENS POR MUNICIPIO

class GeraGrafico extends Component{
    constructor(props){
        super(props);
        this.state = {
            listaMedia:[], 
            listaMunicipio:[]
        }
    }
    
    componentWillMount(){
        console.log("MOUNT");
		$.ajax({
            url:"http://localhost:10774/sbrp-service/rest/grafico/viagens_municipio",
			dataType: 'json',
			success:function(resposta){
                console.log(resposta);
                var i;
				for (i = 0; i < resposta.length; i++) { 
						this.state.listaMedia.push(resposta[i].media);
						this.state.listaMunicipio.push(resposta[i].municipio);
				}
			}.bind(this)
			}
		);
	}
    
    render(){
        return(
            <div>
                <Bar    
                    data={{
                        labels: this.state.listaMunicipio,
                        datasets: [
                        {
                            data: this.state.listaMedia,
                            backgroundColor: 'rgba(0, 0, 0, 1)'
                        }]
                    }}
                    options={{
                        legend:{
                            display: false
                        }
                    }}
                    
                />
            </div>
        )
    }
}
export default class GraficoViagensMunicipio extends Component {
	render() {  
		return (
			<div>
				<div className="box box-primary">
					<div id="ViagemMunicipio" className="box-body">
						<GeraGrafico/>
					</div>
				</div>
			</div>
		);
	}
}

I'm developing an application using React, in which I search the database and graphically present the data on the screen of my application. However, the graph appears empty even with the data being loaded by the back end (I can check this with console.log ()).

After changing the dimensions of the application page (for example, inspecting the element), the data is displayed in the graphic.

Have you been through this? Do you know how I can solve it?

    
asked by anonymous 21.10.2018 / 15:37

3 answers

0

Your code has some improvement points, but I think your problem is two things: Because you are making the request before the component is mounted and you are modifying the state directly (hint: never do this.Read about here ).

First of all, the componentWillMount() method is already being marked as unsafe by the FB staff. So that alone should be enough reason to change. But even so, in the link you read that setting the state within it does not cause re-render , so you will not achieve the goal you want anyway. To get there, use componentDidMount() . Within it, if you change the state, re-render will be triggered and you will eventually reach your goal.

The other point, as I said above, is to modify the state directly. To change it, always (and I always say ) use setState() . This way, you can replace your componentWillMount() with

componentDidMount() {
    console.log("MOUNT");
    $.ajax({
        url:"http://localhost:10774/sbrp-service/rest/grafico/viagens_municipio",
        dataType: 'json',
        success:function(resposta) {
            console.log(resposta);

            const novaListaMedia = [];
            const novaListaMunicipio = [];

            for (let i = 0; i < resposta.length; i++) { 
                novaListaMedia.push(resposta[i].media);
                novaListaMunicipio.push(resposta[i].municipio);
            }

            this.setState({
                listaMedia: novaListaMedia,
                listaMunicipio: novaListaMunicipio
            });
        }
    }.bind(this));
};

Still, I recommend using a leaner, leaner library to work with asynchronous requests, such as axios . Since you're using React, you can use some more modern JavaScript concepts, and this library uses several! =)

    
23.10.2018 / 01:51
1

Your data may not be in the proper format expected by react-chartjs-2, which would cause the component to load, however without displaying any data type. I suggest you post some code snippet so I can try to help.

    
22.10.2018 / 19:49
0

The error may be in the life cycle of your component and your data. In this case the data arrives after rendering your component, then the component is rendered empty (no data).

    
22.10.2018 / 17:13