diff --git a/ReactWithDotNet/ElementSerializer.ToJsonMap.cs b/ReactWithDotNet/ElementSerializer.ToJsonMap.cs index ba0b7d0d..4e9d8f1d 100644 --- a/ReactWithDotNet/ElementSerializer.ToJsonMap.cs +++ b/ReactWithDotNet/ElementSerializer.ToJsonMap.cs @@ -426,15 +426,9 @@ public static async Task ToJsonMap(this Element element, Eleme if (node.FunctionalComponent.Constructor is not null) { await node.FunctionalComponent.Constructor.Invoke(); - - // recalculate scope because maybe fields have changed - node.FunctionalComponent.Scope = SerializationHelperForCompilerGeneratedClasss.Serialize(node.FunctionalComponent.Constructor.Target); - } - else - { - // recalculate scope because maybe fields have changed - node.FunctionalComponent.Scope = SerializationHelperForCompilerGeneratedClasss.Serialize(node.FunctionalComponent._target); } + + node.FunctionalComponent.CalculateScopeFromTarget(); } diff --git a/ReactWithDotNet/FC.cs b/ReactWithDotNet/FC.cs index 074012ff..9731eefa 100644 --- a/ReactWithDotNet/FC.cs +++ b/ReactWithDotNet/FC.cs @@ -42,6 +42,31 @@ sealed class FunctionalComponent : Component, Scope /// public IReadOnlyDictionary Scope { get; set; } + internal void CalculateScopeFromTarget() + { + object target; + + if (renderFuncWithScope is not null) + { + target = renderFuncWithScope.Target; + } + else if (renderFuncAsyncWithScope is not null) + { + target = renderFuncAsyncWithScope.Target; + } + else + { + target = _target; + } + + if (target is null) + { + throw DeveloperException("Invalid usage of useState. target not calculated."); + } + + Scope = SerializationHelperForCompilerGeneratedClasss.Serialize(target); + } + public void InitializeTarget() { _target ??= SerializationHelperForCompilerGeneratedClasss.Deserialize(CompilerGeneratedType, Scope);