I started getting the following error when passing data to a react-chartjs-2 chart component after upgrading react-chartjs-2. It was all working fine before the upgrade so I’m not sure what exactly is causing this issue.
TS2322: Type '{ labels: string[]; datasets: never[]; } | ((canvas: HTMLCanvasElement) => { labels: string[]; datasets: DataSet[]; })' is not assignable to type 'ChartData<"line", (number | ScatterDataPoint | null)[], string>'.
Property 'datasets' is missing in type '(canvas: HTMLCanvasElement) => { labels: string[]; datasets: DataSet[]; }' but required in type 'ChartData<"line", (number | ScatterDataPoint | null)[], string>'.
I’m passing the data like this:
<Line
data={getDataForChart}
options={options}
width={400}
height={400}
/>
My dataset type looks like this:
type DataSet = {
label: string;
data: number[];
fill: boolean;
backgroundColor: CanvasGradient | undefined;
borderColor: string;
pointRadius: number[];
pointBackgroundColor: string;
};
And my getDataForChart
function looks like this:
const getDataForChart = (canvas: HTMLCanvasElement) => {
const dateLabels: string[] = [];
const datasets: DataSet[] = [];
const chart = canvas.getContext('2d') as CanvasRenderingContext2D;
if (scores) {
for (let i = 0; i < assessments.length; i++) {
dateLabels.unshift(formatWithLocale(assessments[i].userAssessment.finishedAt, 'MM/dd'));
}
for (let scoreIndex = 0; scoreIndex < scores.length; scoreIndex++) {
const values: number[] = [];
const pointRadius: number[] = [];
const currentColorIndex = getColorIndex(scoreIndex);
const transparentColor = colors[currentColorIndex].split(')')[0].concat(', 0.3)');
const gradient = chart.createLinearGradient(0, 0, 0, 600);
gradient.addColorStop(0, transparentColor);
gradient.addColorStop(0.6, transparentBlackColor);
for (let assessmentIndex = 0; assessmentIndex < assessments.length; assessmentIndex++) {
const currentScore = assessments[assessmentIndex].userAssessment.scores?.find(
(score) => score.name === scores[scoreIndex].name
);
if (assessmentIndex === assessments.length - 1) {
pointRadius.push(7);
} else {
pointRadius.push(3);
}
if (currentScore) {
values.unshift(currentScore.score);
}
}
if (selectedScore && selectedScore.name !== scores[scoreIndex].name) {
continue;
}
datasets.push({
label: intl.formatMessage({
id: scores[scoreIndex].name,
defaultMessage: scores[scoreIndex].name,
}),
data: values,
fill: true,
backgroundColor: gradient,
borderColor: colors[currentColorIndex],
pointRadius,
pointBackgroundColor: colors[currentColorIndex],
});
}
}
return {
labels: dateLabels,
datasets,
};
};