Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Blazor Apexcharts Line Chart line not being redrawn when new data available

$
0
0

I am trying to show the date on a apexgraph for each schift. When i select a day the data loads and shows no problem. but if i select a new day after i have another day selected the data loads correctly but its not changing the graph. So it still shows the previous day.

and no matter what i do it will not rerender or update.

@Code

private List<spGetDailyReportPloegen>? DagRapportPloegen;private List<spGetGraphPloegen>? GraphVroege;private List<spGetGraphPloegen>? GraphLate;private List<spGetGraphPloegen>? GraphNacht;private long _selectedMachineId; // Initialize to 0 for "All Machines" or a defaultprivate long SelectedMachineId{    get => _selectedMachineId;    set    {        if (_selectedMachineId != value)        {            _selectedMachineId = value;            // Only load data if the component is already initialized and the change is not part of the initial setup            if (_isInitialized)            {                _ = LoadDataAsync(true); // Indicate that this load is due to a filter change            }        }    }}private DateTime? _dag = DateTime.Today;private DateTime? Dag{    get => _dag;    set    {        if (_dag != value)        {            _dag = value;            // Initialize chart options for each chart            InitializeChartOptions();            _ = LoadDataAsync(true);        }    }}private ApexChartOptions<spGetGraphPloegen> chartOptionsVroege;private ApexChartOptions<spGetGraphPloegen> chartOptionsLate;private ApexChartOptions<spGetGraphPloegen> chartOptionsNacht;private void InitializeChartOptions(){    // Get the selected date for dynamic axis range    DateTime selectedDate = _dag?.Date ?? DateTime.Today.Date;    // Y-axis range (adjust these based on your expected 'Cap_Act' values)    double yAxisMin = 0;    double yAxisMax = 600; // Example: assuming capacity goes up to 600 units/hour    int yAxisTickAmount = 3; // Number of ticks on the Y-axis    // Common Y-Axis Configuration (for all charts)    var commonYAxis = new List<YAxis>    {        new YAxis        {            Min = yAxisMin,            Max = yAxisMax,            TickAmount = yAxisTickAmount,            Labels = new YAxisLabels            {                Formatter = @"function (value) { return value.toFixed(0) +' st/u' }" // Format as "X st/u"            }        }    };    // Vroege Ploeg (5:30 - 14:30)    var vroegeMin = new DateTimeOffset(selectedDate.AddHours(5).AddMinutes(30)).ToUnixTimeMilliseconds();    var vroegeMax = new DateTimeOffset(selectedDate.AddHours(14).AddMinutes(30)).ToUnixTimeMilliseconds();    chartOptionsVroege = new()        {            Chart = new Chart            {                Animations = new Animations { Enabled = false },                Zoom = new Zoom { Enabled = false }            },            Xaxis = new XAxis            {                Type = XAxisType.Datetime,                Min = vroegeMin,                Max = vroegeMax,                TickAmount = (int)((vroegeMax - vroegeMin) / (1000 * 60 * 60)), // Tick per hour within the range                Labels = new XAxisLabels                {                    Format = "HH:mm"                },                Tooltip = new XAxisTooltip                {                    Enabled = false                }            },            Yaxis = commonYAxis        };    // Late Ploeg (13:30 - 22:30)    var lateMin = new DateTimeOffset(selectedDate.AddHours(13).AddMinutes(30)).ToUnixTimeMilliseconds();    var lateMax = new DateTimeOffset(selectedDate.AddHours(22).AddMinutes(30)).ToUnixTimeMilliseconds();    chartOptionsLate = new()        {            Chart = new Chart            {                Animations = new Animations { Enabled = false },                Zoom = new Zoom { Enabled = false }            },            Xaxis = new XAxis            {                Type = XAxisType.Datetime,                Min = lateMin,                Max = lateMax,                TickAmount = (int)((lateMax - lateMin) / (1000 * 60 * 60)), // Tick per hour within the range                Labels = new XAxisLabels                {                    Format = "HH:mm"                },                Tooltip = new XAxisTooltip                {                    Enabled = false                }            },            Yaxis = commonYAxis        };    // Nacht Ploeg (21:30 - 6:30 of next day)    // This requires careful handling as it crosses midnight.    // The start time is on the selected date, and the end time is on the *next* date.    var nachtMin = new DateTimeOffset(selectedDate.AddHours(21).AddMinutes(30)).ToUnixTimeMilliseconds();    var nachtMax = new DateTimeOffset(selectedDate.AddDays(1).AddHours(6).AddMinutes(30)).ToUnixTimeMilliseconds();    chartOptionsNacht = new()        {            Chart = new Chart            {                Animations = new Animations { Enabled = false },                Zoom = new Zoom { Enabled = false }            },            Xaxis = new XAxis            {                Type = XAxisType.Datetime,                Min = nachtMin,                Max = nachtMax,                TickAmount = (int)((nachtMax - nachtMin) / (1000 * 60 * 60)), // Tick per hour within the range                Labels = new XAxisLabels                {                    Format = "HH:mm"                },                Tooltip = new XAxisTooltip                {                    Enabled = false                }            },            Yaxis = commonYAxis        };}// Flag to ensure LoadDataAsync is not called by property setters during initial loadprivate bool _isInitialized = false;protected override async Task OnInitializedAsync(){    PageTitleService.SetTitle("Zakkenmachine's • Dagrapport");    // Load machines first    machines = await Http.GetFromJsonAsync<List<Oee_Alg_Machines>>("DagRapport/Machine");    // Set the default selected machine ID if machines are available    if (machines != null && machines.Any())    {        _selectedMachineId = machines.FirstOrDefault()?.Id ?? 10; // Directly set the backing field    }    // Initialize chart options for the initial load    InitializeChartOptions();    // Now that initial setup is done, mark the component as initialized    _isInitialized = true;    // Finally, load the main data once    await LoadDataAsync(false);}private async Task LoadDataAsync(bool isFilterChange = false) // Added parameter to differentiate between initial load and filter change{    // This check is now less critical for preventing double-initial calls, but still good for general logic flow    if (!_isInitialized && isFilterChange)    {        // If it's a filter change but the component isn't fully initialized,        // it means a filter was changed before initial data was loaded.        // This might happen if properties are set before OnInitializedAsync completes.        // In most cases, this `if` block can be removed as the _isInitialized flag prevents the issue more directly.        return;    }    if (Dag == null) // Check for null date, not Day == 0 as Day can't be 0 for a valid DateTime    {        if (isFilterChange)        {            Snackbar.Add("Selecteer alstublieft een datum.", Severity.Warning);        }        DagRapportPloegen = new List<spGetDailyReportPloegen>();        GraphVroege = new List<spGetGraphPloegen>();        GraphLate = new List<spGetGraphPloegen>();        GraphNacht = new List<spGetGraphPloegen>();        StateHasChanged();        return;    }    var requestObj = new DateAndLongDto        {            MachineId = SelectedMachineId,            ProductionDate = Dag        };    var requestObjVroege = new DateAndLongDto        {            MachineId = SelectedMachineId,            ProductionDate = Dag,            PloegId = 1        };    var requestObjLate = new DateAndLongDto        {            MachineId = SelectedMachineId,            ProductionDate = Dag,            PloegId = 2        };    var requestObjNacht = new DateAndLongDto        {            MachineId = SelectedMachineId,            ProductionDate = Dag,            PloegId = 3        };    try    {        var response = await Http.PostAsJsonAsync("DagRapport/DagRapportPloegen", requestObj);        var responseVroege = await Http.PostAsJsonAsync("DagRapport/Graphs", requestObjVroege);        var responseLate = await Http.PostAsJsonAsync("DagRapport/Graphs", requestObjLate);        var responseNacht = await Http.PostAsJsonAsync("DagRapport/Graphs", requestObjNacht);        response.EnsureSuccessStatusCode();        responseVroege.EnsureSuccessStatusCode();        responseLate.EnsureSuccessStatusCode();        responseNacht.EnsureSuccessStatusCode();        DagRapportPloegen = await response.Content.ReadFromJsonAsync<List<spGetDailyReportPloegen>>();        GraphVroege = await responseVroege.Content.ReadFromJsonAsync<List<spGetGraphPloegen>>();        GraphLate = await responseLate.Content.ReadFromJsonAsync<List<spGetGraphPloegen>>();        GraphNacht = await responseNacht.Content.ReadFromJsonAsync<List<spGetGraphPloegen>>();        if (isFilterChange && (DagRapportPloegen == null || DagRapportPloegen.Count == 0))        {            Snackbar.Add("Geen records gevonden voor de geselecteerde filter.", Severity.Info);        }    }    catch (HttpRequestException httpEx)    {        Console.Error.WriteLine($"HTTP Fout bij het laden van gegevens: {httpEx.Message}");        Snackbar.Add($"Fout bij het ophalen van gegevens: {httpEx.Message}", Severity.Error);    }    catch (Exception ex)    {        Console.Error.WriteLine($"Er is een onverwachte fout opgetreden: {ex.Message}");        Snackbar.Add($"Er is een onverwachte fout opgetreden: {ex.Message}", Severity.Error);    }    StateHasChanged(); // Refresh UI}

View

<MudItem xs="12" sm="12" md="12"><MudText Typo="Typo.h6" Align="MudBlazor.Align.Center">Vroege Ploeg</MudText>    @if (GraphVroege != null && GraphVroege.Any())    {<ApexChart TItem="spGetGraphPloegen" Options="chartOptionsVroege" Height="300"><ApexPointSeries TItem="spGetGraphPloegen"                             Items="GraphVroege"                             Name="Vroege"                             SeriesType="SeriesType.Line"                             XValue="e => e.Ts"                             YValue="e => (decimal)e.Cap_Act" /></ApexChart>    }    else    {<MudText Align="MudBlazor.Align.Center">Geen gegevens beschikbaar voor Vroege Ploeg.</MudText>    }</MudItem><MudItem xs="12" sm="12" md="12"><MudText Typo="Typo.h6" Align="MudBlazor.Align.Center">Late</MudText>    @if (GraphLate != null && GraphLate.Any())    {<ApexChart TItem="spGetGraphPloegen" Options="chartOptionsLate" Height="300"><ApexPointSeries TItem="spGetGraphPloegen"                             Items="GraphLate"                             Name="Late"                             SeriesType="SeriesType.Line"                             XValue="e => e.Ts"                             YValue="e => (decimal)e.Cap_Act" /></ApexChart>    }    else    {<MudText Align="MudBlazor.Align.Center">Geen gegevens beschikbaar voor Late Ploeg.</MudText>    }</MudItem><MudItem xs="12" sm="12" md="12"><MudText Typo="Typo.h6" Align="MudBlazor.Align.Center">Nacht</MudText>    @if (GraphNacht != null && GraphNacht.Any())    {<ApexChart TItem="spGetGraphPloegen" Options="chartOptionsNacht" Height="300"><ApexPointSeries TItem="spGetGraphPloegen"                             Items="GraphNacht"                             Name="Nacht"                             SeriesType="SeriesType.Line"                             XValue="e => e.Ts"                             YValue="e => (decimal)e.Cap_Act" /></ApexChart>    }    else    {<MudText Align="MudBlazor.Align.Center">Geen gegevens beschikbaar voor Nacht Ploeg.</MudText>    }</MudItem>

Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>