[Chartjs]-Line not drawn in Line chart with react-chartjs-2

1👍

You should also set xAxisKey in parsing. It seems logical that the library would use period since you defined the labels as such, but apparently it doesn’t make that infferrence by itself.

Here’s a non-react example based on your code, with invented data:

const dataFromDb = [
    {period: '2019', price_so: 100, price_po: 110},
    {period: '2020', price_so: 120, price_po: 120},
    {period: '2021', price_so: 110, price_po: 109},
    {period: '2022', price_so: 90, price_po: 100},
    {period: '2023', price_so: 105, price_po: 115},
];
const data = {
    labels: dataFromDb.map(item => item.period),
    datasets: [
        {
            data: dataFromDb,
            backgroundColor: '#FAA46A',
            borderColor: '#FAA46A',
            label: 'sellPrice',
            parsing: { xAxisKey: 'period', yAxisKey: 'price_so' },
        },
        {
            data: dataFromDb,
            backgroundColor: '#1DCF35',
            borderColor: '#1DCF35',
            label: 'purchasePrice',
            parsing: { xAxisKey: 'period', yAxisKey: 'price_po' },
        },
    ],
};

const options={
    animation: false,
    maintainAspectRatio: false,
    /*elements: { line: { tension: 0.4 } },*/
    scales: {
        x: { grid: { display: false }, offset: true },
        y: {
            title: { text: 'amount', display: true },
            grid: { display: false },
        },
    },
};

new Chart(document.querySelector('#line-chart'), {type:'line', data, options});
<div id="line-chart-container">
<canvas id="line-chart"></canvas>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.1.2/chart.umd.js"
        integrity="sha512-t41WshQCxr9T3SWH3DBZoDnAT9gfVLtQS+NKO60fdAwScoB37rXtdxT/oKe986G0BFnP4mtGzXxuYpHrMoMJLA=="
        crossorigin="anonymous" referrerpolicy="no-referrer">
</script>

Leave a comment