JLCarveth
JLCarveth

Reputation: 123

Chart.js throwing an error when funciton used to populate data

I am using Chart.js and react-chartjs-2 to add charts to my React application.

I am trying to load data into a chart as follows:

<Chart type="line" data={this.getData}/>

getData is a simple function which converts the data in the component's props into a format Chart.js understands:

function getData() {
    const data = this.props.data;
    [...]
    return {
        labels: dates // This is an array of dates as strings, ex ["2022-11-14", ...]
        datasets: [{ label: "Some Label", data: sales}] // sales is an array of numbers
    }
}

However, when I load the Chart I get the following error:

TypeError: t is undefined

This error goes away if I hardcode the data into the component, ie:

<Chart type="line" data={{
    labels: ["one", "two", "three"]
    datasets: [{ label: "Some Label", data: [1,2,3]}]
}}/>

So despite the fact that getData() returns data in the exact same way that it's hardcoded, that error is thrown if I use getData() instead of hardcoding the chart data.

Upvotes: 0

Views: 44

Answers (1)

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41377

You are calling a function inside the data so add the missing parenthesis

<Chart type="line" data={this.getData()}/>

Upvotes: 1

Related Questions