Error when rendering BarChart in OnInitializedAsync [TypeError: Cannot read property 'options' of undefined]
victormarante opened this issue · comments
Victor Marante commented
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?
- Server-Side
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);
}
}