Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NullReferenceException when viewing chart #178

Open
ADringer opened this issue Feb 14, 2021 · 3 comments
Open

NullReferenceException when viewing chart #178

ADringer opened this issue Feb 14, 2021 · 3 comments
Labels
bug Something isn't working

Comments

@ADringer
Copy link

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?

  • Client-Side

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!

@ADringer ADringer added the bug Something isn't working label Feb 14, 2021
@fleed
Copy link

fleed commented May 17, 2021

@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
Copy link
Author

@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
Copy link

pgrimstrup commented May 29, 2021

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

3 participants