Skip to content

[Blazor] @key is not respected for interactive WebAssembly components after publish #53289

Closed
@MackinnonBuck

Description

@MackinnonBuck

Summary

Components with InteractiveWebAssembly render modes cannot receive parameter updates from SSR updates on published apps. If the component receives any changed parameters, it always gets destroyed and re-initialized regardless of whether a matching @key was present.

Steps to reproduce

  1. dotnet new blazor -int WebAssembly
  2. Add a CounterButton component in the .Client project:
    @inject NavigationManager NavigationManager
    
    <p role="status">Current count: @currentCount</p>
    
    <button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
    <button class="btn btn-secondary" @onclick="RefreshPage">Refresh</button>
    
    @code {
        private int currentCount = 0;
    
        [Parameter]
        [EditorRequired]
        public int IncrementAmount { get; set; }
    
        private void IncrementCount()
        {
            currentCount += IncrementAmount;
        }
    
        private void RefreshPage()
        {
            NavigationManager.Refresh();
        }
    }
  3. Update Home.razor:
    @page "/"
    
    <PageTitle>Home</PageTitle>
    
    <h1>Hello, world!</h1>
    
    <p>Page load count: @pageLoadCount</p>
    
    <CounterButton @key="0" @rendermode="InteractiveWebAssembly" IncrementAmount="@pageLoadCount" />
        
    @code {
        private static int pageLoadCount = 0;
    
        protected override void OnInitialized()
        {
            pageLoadCount++;
        }
    }
  4. Run the app using dotnet run
  5. Click "Click me" and then click "Refresh" and observe that the counter retains its state
  6. Publish the app using dotnet publish
  7. Run the published app
  8. Click "Click me" and then click "Refresh" and observe that the counter loses its state

Other notes

This appears to be a trimming issue, since doing the following solves the problem:

  1. Update the .Client.csproj file to include:
    <ItemGroup>
      <TrimmerRootDescriptor Include="Roots.xml" />
    </ItemGroup>
  2. Add a Roots.xml file to the .Client folder:
    <linker>
      <assembly fullname="Microsoft.AspNetCore.Components.WebAssembly" preserve="all">
      </assembly>
    </linker>

.NET SDK Version: 8.0.100

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

Status

Done

Relationships

None yet

Development

No branches or pull requests

Issue actions