mariusmuntean / ChartJs.Blazor

Brings Chart.js charts to Blazor
https://www.iheartblazor.com/
MIT License
676 stars 151 forks source link

Error when rendering BarChart in OnInitializedAsync [TypeError: Cannot read property 'options' of undefined] #196

Open victormarante opened 2 years ago

victormarante commented 2 years ago

Describe your question

How to correctly use BarCharts with data from asynchrounous call in OnInitializedAsync. I have a situation where I need to get data from an API, and then use that data to render the charts (or at least populate the data). When I run the code in the section below, I get the error in the attached image.

Which Blazor project type is your question related to?

Which charts is this question related to?

BarChart

Additional context

I have made a oversimplified example that illustrates what I am trying to do. Hope this provides enough information for you to help me.

I have the following code:

@page "/barchart"
@using ChartJs.Blazor.BarChart
@using System.Drawing

<h3>BarChartTest</h3>

<Chart Config="_pricePerWorkerBarChartConfig" @ref="_pricePerWorkerBarChart"></Chart>

@code {
    protected readonly BarConfig _pricePerWorkerBarChartConfig = new();
    protected Chart _pricePerWorkerBarChart;

    protected override async Task OnInitializedAsync()
    {
        RenderBarChartForPricePerWorker();

        await Task.Delay(1500);
    }

    private void RenderBarChartForPricePerWorker()
    {
        _pricePerWorkerBarChartConfig.Options = new BarOptions
        {
            Responsive = true,
            Legend = new Legend
            {
                Position = Position.Top,
            },
            Title = new OptionsTitle
            {
                Display = true,
            },
        };

        var dataSet = new BarDataset<double>(
            new[]
            {
                150.90,
                123.73,
                155.66,
                1634.12,
            })
        {
            Label = "My first dataset",
            BackgroundColor = ColorUtil.FromDrawingColor(Color.FromArgb(128, Utils.ChartColors.Red)),
            BorderColor = ColorUtil.FromDrawingColor(Utils.ChartColors.Red),
            BorderWidth = 1,
            YAxisId = "Cost",
            XAxisId = "Worker",
        };

        foreach (var worker in new[]{ "Person1", "Person2", "Person3", "Person4"})
        {
            _pricePerWorkerBarChartConfig.Data.Labels.Add(worker);
        }

        _pricePerWorkerBarChartConfig.Data.Datasets.Add(dataSet);
    }
}

Image of error: image