Skip to content

PersistentState being lost with multiple calls to OnParametersSetAsync #63435

@kwise990

Description

@kwise990

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

There does not seem to be a way to use PersistentState when OnParametersSetAsync is being called multiple times. The property is always null.

@page "/counter"

<PageTitle>Prerendered Counter 2</PageTitle>

<h1>Prerendered Counter 2</h1>

<p role="status">Current count: @State?.CurrentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    [Parameter] 
    public int? SompeParameter { get; set; }

    [PersistentStateAttribute]
    public CounterState? State { get; set; }
    
    protected override async Task OnInitializedAsync()
    {
        if (State is null)
        {
            State = new() { CurrentCount = Random.Shared.Next(100) }; 
        }
    }

    protected override async Task OnParametersSetAsync()
    {
        //This runs twice because SompeParameter is being set in the parent after a delay
        //When this runs State is always null and resets State to null
    }

    private void IncrementCount()
    {
        if (State is not null)
        {
            State.CurrentCount++;
        }
    }

    public class CounterState
    {
        public int CurrentCount { get; set; }
    }
}

Expected Behavior

The parameter should only be around once and most likely in OnInitializedAsync.

Steps To Reproduce

Maybe I am using this feature incorrectly. PersistenState seems to work great when no parameters are passed to the component as in most examples i have found.

Exceptions (if any)

No response

.NET Version

10.0.0-preview.7.25380.108

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-blazorIncludes: Blazor, Razor Components

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions