mariusmuntean / ChartJs.Blazor

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

NullReferenceException when viewing chart #178

Open ADringer opened 3 years ago

ADringer commented 3 years ago

Describe the bug

I have a strong feeling it's a user issue, but I'm getting the following error when trying to view a chart in my wasm project:

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object.
  at ChartJs.Blazor.Chart.BuildRenderTree (Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) <0x3b3d7a0 + 0x00026> in <filename unknown>:0 
  at Microsoft.AspNetCore.Components.ComponentBase.<.ctor>b__6_0 

Which Blazor project type is your bug related to?

Which charts does this bug apply to?

Bar chart

To Reproduce

Steps to reproduce the behavior: Create a Blazor WASM project.

Added the following to index.html in the client app:

    <script src="_framework/blazor.webassembly.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>
    <script src="_content/ChartJs.Blazor.Fork/ChartJsBlazorInterop.js"></script>
    <script>navigator.serviceWorker.register('service-worker.js');</script>
</body>

The following in _imports.razor:

@using ChartJs.Blazor
@using ChartJs.Blazor.Common
@using ChartJs.Blazor.Common.Axes
@using ChartJs.Blazor.Common.Axes.Ticks
@using ChartJs.Blazor.Common.Enums
@using ChartJs.Blazor.Common.Handlers
@using ChartJs.Blazor.Common.Time
@using ChartJs.Blazor.Util
@using ChartJs.Blazor.Interop

And the razor component:

@page "/consumption"
@using EnergyUsageApp.Shared
@using System.Text.Json
@using ChartJs.Blazor.BarChart
@inject HttpClient Http

<Chart Config="_chart" @ref="chartjs"></Chart>

@code {
    private Chart chartjs;

    BarConfig _chart;

    protected override async Task OnInitializedAsync()
    {
        var date = JsonSerializer.Serialize(SelectedDate).Replace("\"", "");
        var periodCosts = await Http.GetFromJsonAsync<PeriodCost[]>($"url}");

_chart = new BarConfig
        {
            Options = new BarOptions
            {
                Responsive = true,
                Legend = new Legend
                {
                    Position = Position.Top
                },
                Title = new OptionsTitle
                {
                    Display = true,
                    Text = "ChartJs.Blazor Bar Chart"
                }
            }
        };

        var dataset = new BarDataset<double>(new double[] { 2, 2, 2});
        _chart.Data.Datasets.Add(dataset);

        var dataset2 = new ChartJs.Blazor.LineChart.LineDataset<double>(new double[] {2, 4 ,6 });
        _chart.Data.Datasets.Add(dataset2);

        new string[] {"Jan", "Feb", "Mar"}.ForEach(x => _chart.Data.Labels.Add(x));
       await chartjs.Update();

Expected behavior

Error logged in the console.

I imagine I've done something obviously wrong, so apologies for using your time!

fleed commented 3 years ago

@ADringer I'm running into the same exception with a different library, anyway the scenario is the same: getting data from an external source through an HTTP request. Were you able to fix it somehow? It seems more something related to the framework rather than something specific to the libraries

ADringer commented 3 years ago

@fleed yes, was able to get round this by moving my code round a little.

The issue I think is mainly with the OnInitializedAsync() override. So what I've done is moved my chart initialization into the OnInitialized() override instead e.g:

protected override void OnInitialized()
{
      _chart = new BarConfig
      { ... }
}

And then do the async HTTP call in the OnAfterRenderAsync override instead:

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
       {
          // HTTP call
       }
}

Hope that helps!

pgrimstrup commented 3 years ago

This looks like a timing issue. The OnInitializedAsync call may not have been completed before Blazor makes its first render, so _chart would have been null. There are three ways you can work around this:

  1. Set the _chart variable to a default value in the constructor or as an initializer (eg BarConfig _chart = new BarConfig(). Replace the _chart variable when you get the data and call StateHasChanged()
  2. Set the _chart variable to a default value and add in the datasets when the data is returned. Since this is an async method, you could then call InvokeAsync(StateHasChanged).
  3. Wrap the component in an @if statement: @if(_chart != null){ <Chart Config="_chart" @ref="chartjs"></Chart> }

I'll go ahead and close this issue.