[SOLVED] Chart.js Instantiation Error

[SOLVED] Chart.js Instantiation Error
0

#1

For those who worked on the voting app project, did any of you use chart js? I’ve followed the documentation to the letter, and I’m getting the error:
Uncaught (in promise) TypeError: Cannot read property ‘length’ of null
at acquireContext (bundle.js:65850)
at new Chart.Controller (bundle.js:65903)
at new Chart (bundle.js:62577)
at ChartVisual.render (bundle.js:89186)
And this is my code: (I intentionally left out the return content for the sake of brevity, but it contains the required canvas element to be passed in to the constructor.)

const colors = ["#ff0000", "#ffff00", "#ffa500", "#008000", "#800080", "#ff00ff", "#0000ff", "#9acd32", "#00ff00", "#00ced1", "#d2691e"];
        const data = {
            labels: this.props.choices,
                datasets: [{
                    data: this.props.chartData,
                    backgroundColor: chartColors,
                    hoverBackgroundColor: chartColors
                }]
        }
        let chartColors = colors.slice(0, this.props.choices.length);
        let ctx = document.getElementById("dataChart");
        let chart = new Chart(ctx, {
            type: "doughnut",
            data: data
        });

#2

The error seems to suggest this.props.choices is equal to null. Can you log it?


#3

Wow thanks for the quick reply! And yeah I checked my props already, it’s defined. Based on the logs I did, the error happens after I put the canvas element into a variable.


#4

Do you have a Codepen?

EDIT My bad it is the voting app, Github maybe?


#5

Yeah, here’s my git repo: https://github.com/codefu-chivy/pollers-app


#6

You should really use a .gitignore file. Your username and password for your database should not be uploaded to Github.


#7

Yeah, I know…I had uploaded my files pretty hastily. I’ll make sure to correct this. I had used an env file to hide my passwords but for some reason it wasn’t working. Should the env file go into the root directory?


#8

Not sure if that matters, as long as you add inside your .gitignore.

I have to admit I don’t have much experience with React, but is ctx defined? I mean, can you access DOM elements that are inside of the return( ... )?


#9

Aha! I did not check that before. I tried logging ctx to the console and it is indeed null. Not sure why though. I thought it was possible to access virtual DOM elements from the render function. I’ll have to figure out another way then. Thanks for pointing that out!


#10

Got it! I used one of the React lifecycle methods, “componentDidMount” to make sure that the element was loaded before storing it into the variable.