I’m trying to implement the persistent state of prerender in blazor, but it’s only working when I go directly to the component shown below. If I go to that component and then to another one and come back or open another component first and then go to this one, it will already make the call to the API twice, instead of just once. This applies when it’s InteractiveServer, InteractiveAuto and InteractiveWebAssembly.
@page "/auth"
@implements IDisposable
@inject PersistentComponentState ApplicationState
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Http
@inject HttpClient client
@attribute [Authorize]
@rendermode InteractiveAuto
<PageTitle>Auth</PageTitle>
<h1>You are authenticated</h1>
<AuthorizeView>
Hello @context.User.Identity?.Name!
</AuthorizeView>
@data
@code {
private const string key = "teste";
string data = "";
private PersistingComponentStateSubscription persistingSub;
[CascadingParameter]
HttpContext? httpContext { get; set; }
protected override async Task OnInitializedAsync()
{
persistingSub = ApplicationState.RegisterOnPersisting(PersistData);
if (!ApplicationState.TryTakeFromJson<string>(key, out var restored))
{
data = await client.GetStringAsync("api/testes");
}
else
{
data = restored!;
}
}
private Task PersistData()
{
ApplicationState.PersistAsJson(key, data);
return Task.CompletedTask;
}
void IDisposable.Dispose()
{
persistingSub.Dispose();
}
}
1