React-chartjs-2 graphics do not load on screen

Asked

Viewed 205 times

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 am developing an application using React, in which I do a search in a database and graphically present the data on the screen of my application. However, the chart appears empty even though the data is loaded by the back end (I can check this with consolation.log()).

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

Have you been there? You know how I can fix?

3 answers

1

It is possible that your data is not in the proper format expected by React-chartjs-2, which would cause the component to be loaded, however without displaying any kind of data. I suggest you publish some piece of code so I can try to help.

  • Thank you for your attention Pedro. I published the code of my component next to the question.

0

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

0


Your code has some improvement points, but I believe your problem is being dealt with by two things: The fact that you are making the request before the component assembles and the fact that you are modifying the state directly (tip: never do that. Read about here).

First: the method of componentWillMount() is already being marked as unsafe by the FB people. So that alone should be reason enough to change. But even so, in the link you read that setting the state within it does not cause the re-surrender, then you won’t achieve the goal you want anyway. To get there, use the componentDidMount(). Inside it, in case you change the state, the re-surrender will be provoked 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 say at all times) use the setState(). That way you can replace your componentWillMount() for

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 more modern and streamlined library to work with asynchronous requests, such as the Xios. Since you are using React, you can use some more modern Javascript concepts, and this library uses several! =)

  • 1

    It worked out Caio! I started messing with React a little while ago, so I don’t have much practice yet. But your answer and the tips helped me a lot here. Thank you very much!

  • @Joãomarcossoares everyone has to start somewhere ;)

Browser other questions tagged

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