Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 22 additions & 13 deletions src/Components/Web.JS/src/Rendering/JSRootComponents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ let nextPendingDynamicRootComponentIdentifier = 0;
type ComponentParameters = object | null | undefined;

let manager: DotNet.DotNetObject | undefined;
let currentRendererId: number | undefined;
let jsComponentParametersByIdentifier: JSComponentParametersByIdentifier;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 Bug: jsComponentParametersByIdentifier is never assigned, breaking add()

The PR removed the line jsComponentParametersByIdentifier = jsComponentParameters; from enableJSRootComponents() (visible in the diff as a deleted line). However, the module-scoped variable jsComponentParametersByIdentifier is still used on line 30:

const component = new DynamicRootComponent(componentId, jsComponentParametersByIdentifier[componentIdentifier]);

Since jsComponentParametersByIdentifier is declared on line 14 but never assigned a value after this change, it will be undefined. Any call to RootComponentsFunctions.add() (the public API for dynamically adding root components) will crash with a TypeError: Cannot read properties of undefined.

The variable needs to be updated each time enableJSRootComponents is called so that newly added dynamic root components can look up their parameter definitions. This is especially important on circuit restart, where a fresh set of parameters may be provided.

Fix: Restore the assignment of jsComponentParametersByIdentifier in the function body (outside the hasInitializedJsComponents guard, so it's updated on every call):

currentRendererId = rendererId;
manager = managerInstance;
jsComponentParametersByIdentifier = jsComponentParameters;  // Add this back

Was this helpful? React with 👍 / 👎

  • Apply suggested fix

let hasInitializedJsComponents = false;

// These are the public APIs at Blazor.rootComponents.*
export const RootComponentsFunctions = {
Expand Down Expand Up @@ -116,28 +118,35 @@ class DynamicRootComponent {

// Called by the framework
export function enableJSRootComponents(
rendererId: number,
managerInstance: DotNet.DotNetObject,
jsComponentParameters: JSComponentParametersByIdentifier,
jsComponentInitializers: JSComponentIdentifiersByInitializer
): void {
if (manager) {
// This will only happen in very nonstandard cases where someone has multiple hosts.
// It's up to the developer to ensure that only one of them enables dynamic root components.
if (manager && currentRendererId === rendererId) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 Bug: Guard condition is inverted: blocks same renderer, allows different

The condition on line 126 (currentRendererId === rendererId) throws an error when the same renderer tries to reinitialize, but allows a different renderer through. This is the opposite of the stated intent.

Current behavior:

  • Same renderer restarts (circuit restart) → currentRendererId === rendererId is truethrows error
  • Different renderer tries to register → currentRendererId === rendererId is falsesilently accepted

Intended behavior (per PR description and comments):

  • Same renderer restarts → should be allowed (update manager reference)
  • Different renderer tries to register → should throw error (unsupported multi-host scenario)

The comment on lines 127-128 is also inconsistent with the condition — it says "A different renderer type is trying to enable JS root components" but the condition matches when renderer IDs are the same.

Fix: Change === to !==:

if (manager && currentRendererId !== rendererId) {

This would correctly block different renderers while allowing same-renderer reinitialization on circuit restart.

Was this helpful? React with 👍 / 👎

Suggested change
if (manager && currentRendererId === rendererId) {
if (manager && currentRendererId !== rendererId) {
  • Apply suggested fix

// A different renderer type (e.g., Server vs WebAssembly) is trying to enable JS root components.
// This is a multi-host scenario which is not supported for dynamic root components.
throw new Error('Dynamic root components have already been enabled.');
}

// When the same renderer type re-enables (e.g., circuit restart or new circuit on same page),
// accept the new manager. The old manager's DotNetObjectReference is no longer valid anyway
// because the old circuit is gone. We don't dispose the old manager - doing so would cause
// JSDisconnectedException because the circuit that created it no longer exists.
currentRendererId = rendererId;
manager = managerInstance;
jsComponentParametersByIdentifier = jsComponentParameters;

// Call the registered initializers. This is an arbitrary subset of the JS component types that are registered
// on the .NET side - just those of them that require some JS-side initialization (e.g., to register them
// as custom elements).
for (const [initializerIdentifier, componentIdentifiers] of Object.entries(jsComponentInitializers)) {
const initializerFunc = DotNet.findJSFunction(initializerIdentifier, 0) as JSComponentInitializerCallback;
for (const componentIdentifier of componentIdentifiers) {
const parameters = jsComponentParameters[componentIdentifier];
initializerFunc(componentIdentifier, parameters);

if (!hasInitializedJsComponents) {
// Call the registered initializers. This is an arbitrary subset of the JS component types that are registered
// on the .NET side - just those of them that require some JS-side initialization (e.g., to register them
// as custom elements).
for (const [initializerIdentifier, componentIdentifiers] of Object.entries(jsComponentInitializers)) {
const initializerFunc = DotNet.findJSFunction(initializerIdentifier, 0) as JSComponentInitializerCallback;
for (const componentIdentifier of componentIdentifiers)
initializerFunc(componentIdentifier, jsComponentParameters[componentIdentifier]);
}

hasInitializedJsComponents = true;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export function attachWebRendererInterop(

if (jsComponentParameters && jsComponentInitializers && Object.keys(jsComponentParameters).length > 0) {
const manager = getInteropMethods(rendererId);
enableJSRootComponents(manager, jsComponentParameters, jsComponentInitializers);
enableJSRootComponents(rendererId, manager, jsComponentParameters, jsComponentInitializers);
}

rendererByIdResolverMap.get(rendererId)?.[0]?.();
Expand Down
42 changes: 0 additions & 42 deletions src/Components/test/E2ETest/Tests/StatePersistanceJSRootTest.cs

This file was deleted.

14 changes: 14 additions & 0 deletions src/Components/test/E2ETest/Tests/StatePersistenceTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,20 @@ public async Task StateIsProvidedEveryTimeACircuitGetsCreated(string streaming)
RenderComponentsWithPersistentStateAndValidate(suppressEnhancedNavigation: false, mode, typeof(InteractiveServerRenderMode), streaming, stateValue: "other");
}

[Theory]
[InlineData("ServerNonPrerendered")]
[InlineData("WebAssemblyNonPrerendered")]
public void PersistentStateIsSupportedInDynamicJSRoots(string renderMode)
{
Navigate($"subdir/WasmMinimal/dynamic-js-root.html?renderMode={renderMode}");

Browser.Equal("Counter", () => Browser.Exists(By.TagName("h1")).Text);
Browser.Equal("Current count: 0", () => Browser.Exists(By.CssSelector("p[role='status']")).Text);

Browser.Click(By.CssSelector("button.btn-primary"));
Browser.Equal("Current count: 1", () => Browser.Exists(By.CssSelector("p[role='status']")).Text);
}

private void BlockWebAssemblyResourceLoad()
{
// Clear local storage so that the resource hash is not found
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ public static async Task Main(string[] args)
["CORS (WASM)"] = (BuildWebHost<CorsStartup>(CreateAdditionalArgs(args)), "/subdir"),
["Prerendering (Server-side)"] = (BuildWebHost<PrerenderedStartup>(CreateAdditionalArgs(args)), "/prerendered"),
["Razor Component Endpoints"] = (BuildWebHost<RazorComponentEndpointsStartup<App>>(CreateAdditionalArgs(args)), "/subdir"),
["Razor Component Endpoints with JS Root Component"] = (BuildWebHost<RazorComponentEndpointsStartup<App>>(CreateAdditionalArgs([.. args, "--RegisterDynamicJSRootComponent", "true"])), "/subdir"),
["Deferred component content (Server-side)"] = (BuildWebHost<DeferredComponentContentStartup>(CreateAdditionalArgs(args)), "/deferred-component-content"),
["Locked navigation (Server-side)"] = (BuildWebHost<LockedNavigationStartup>(CreateAdditionalArgs(args)), "/locked-navigation"),
["Client-side with fallback"] = (BuildWebHost<StartupWithMapFallbackToClientSideBlazor>(CreateAdditionalArgs(args)), "/fallback"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,7 @@ public void ConfigureServices(IServiceCollection services)
options.DisconnectedCircuitMaxRetained = 0;
options.DetailedErrors = true;
}
if (Configuration.GetValue<bool>("RegisterDynamicJSRootComponent"))
{
options.RootComponents.RegisterForJavaScript<TestContentPackage.PersistentComponents.ComponentWithPersistentState>("dynamic-js-root-counter");
}
options.RootComponents.RegisterForJavaScript<TestContentPackage.PersistentComponents.ComponentWithPersistentState>("dynamic-js-root-counter");
})
.AddAuthenticationStateSerialization(options =>
{
Expand Down