Skip to content

[Blazor] PersistentState throws ArgumentException when using multiple instances of the same component #64608

@mikermnv

Description

@mikermnv

PersistentState throws ArgumentException with multiple component instances

Describe the issue
When using [PersistentState] inside a reusable component that is rendered multiple times on the same page, Blazor throws the following exception rendering this page:

System.ArgumentException: There is already a persisted object under the same key at Microsoft.AspNetCore.Components.Infrastructure.PersistentValueProviderComponentSubscription.PersistProperty() at Microsoft.AspNetCore.Components.Infrastructure.ComponentStatePersistenceManager.<TryPauseAsync>g__TryExecuteCallback|21_0(Func1 callback, ILogger1 logger)
Image

To Reproduce

  1. Create a component with [PersistentState] property (Counter component).
  2. Render multiple instances of this component on the same page (on Home page place Counter component twice).
  3. Start web app.
  4. Observe the exception.

Expected behavior
Each component instance should be able to persist its state independently, without key collisions. Alternatively, documentation should clarify how to generate unique keys per instance.

Sample code
Counter.razor

<PageTitle>Counter</PageTitle>
@rendermode InteractiveServer

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

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

@code {
    [PersistentState] public int? currentCount { get; set; }

    protected override void OnInitialized()
    {
        if (currentCount == null)
        {
            currentCount = 0;
        }
    }
    private void IncrementCount()
    {
        currentCount = 10;
    }
}

Home.Razor

@page "/"

<PageTitle>Home</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.
<Counter/>
<Counter />

Blazor Server (Interective with prerendering)

.NET version: 10.0

Browser: Edge

OS: Windows 11 Pro

Additional notes
From the documentation it appears that [PersistentState] works by serializing the property and then deserializing it later to restore the state. This mechanism works fine when there is only a single instance of the component. However, when multiple instances of the same component exist on the page, they all attempt to persist properties under identical names. As a result, the persistence manager encounters duplicate keys and throws an ArgumentException.

This raises an open question: in scenarios where multiple component instances share the same persisted property names, what is the recommended approach?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions