Skip to content

Commit

Permalink
Update state lifecycle
Browse files Browse the repository at this point in the history
  • Loading branch information
YuriyDurov committed Sep 15, 2024
1 parent 55a3032 commit 895df93
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,20 @@ internal class PersistentComponentRenderStrategy(PersistentComponentBase compone

protected override async Task RunInitAndSetParametersAsync()
{
// Setup state before initializing the component
await SetupStateAsync();
// TODO: Dotnet 9
//if (Handle.RendererInfo.IsInteractive)
var shouldInitializeState = true;
var isInteractive = RendererInfo.IsInteractive;
if (isInteractive)
{
var restored = await TryRestoringStateAsync();
shouldInitializeState = !restored;
}

await base.RunInitAndSetParametersAsync();

if (shouldInitializeState) await InitializeStateAsync();

if (PersistentComponent.StateContainer is not null)
await PersistentComponent.StateContainer!.RefreshAsync();
}
Expand Down Expand Up @@ -56,23 +65,7 @@ private async Task WaitForPageStateAsync()
throw new TimeoutException("Timed out: Page state took too long to restore.");
}

protected virtual async Task SetupStateAsync()
{
if (StateInitialized) throw new InvalidOperationException("State has already been initialized for this component.");

// TODO: Dotnet 9
//if (Handle.RendererInfo.IsInteractive)
if (RendererInfo.IsInteractive)
{
await RestoreStateAsync();
}
else
{
await InitializeStateAsync();
}
}

protected virtual async Task RestoreStateAsync()
protected virtual async Task<bool> TryRestoringStateAsync()
{
if (ShouldWaitForRootStateRestore)
{
Expand All @@ -88,10 +81,7 @@ protected virtual async Task RestoreStateAsync()
if (pageState is null)
{
// Page state not found.
// Initializing state as a fallback.

await InitializeStateAsync();
return;
return false;
}

var path = GetComponentLocation(PersistentComponent);
Expand All @@ -100,16 +90,14 @@ protected virtual async Task RestoreStateAsync()
if (state is null)
{
// Component state not found.
// Initializing state as a fallback.

await InitializeStateAsync();
return;
return false;
}

RestoreComponentState(state);
StateInitialized = true;

PersistentComponent.NotifyStateRestored();
return true;
}

protected void RestoreComponentState(JsonObject state)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ internal override void BuildRenderTree(RenderTreeBuilder builder)
builder.CloseComponent();
}

protected override async Task RestoreStateAsync()
protected override async Task TryRestoringStateAsync()
{
var js = ServiceProvider.GetRequiredService<IJSRuntime>();
var stateBase64 = await js.InvokeAsync<string?>("getInnerText", [PageStateElementId]);
Expand Down

0 comments on commit 895df93

Please sign in to comment.