-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Description
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)
To Reproduce
- Create a component with
[PersistentState]property (Counter component). - Render multiple instances of this component on the same page (on Home page place Counter component twice).
- Start web app.
- 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?