I am able to set the session storage but not access it. I am working in a Blazor server app. I have even debugged and found that userId does not get fetched and its value gets set to 0 when the OnInitializedAsync method of StateProvider component is called.
Here is my code for state provider parent component in StateProvider.razor:
@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
@inject ProtectedSessionStorage ProtectedSessionStore
@if (isLoaded)
{
<CascadingValue Value="@this">
@ChildContent
</CascadingValue>
}
else
{
<p>Loading...</p>
}
@code {
private bool isLoaded;
[Parameter]
public RenderFragment? ChildContent { get; set; }
public int userId { get; set; }
protected override async Task OnInitializedAsync()
{
var result = await ProtectedSessionStore.GetAsync<int>("userId");
userId = result.Success ? result.Value : 0;
isLoaded = true;
}
public async Task SaveChangesAsync()
{
await ProtectedSessionStore.SetAsync("userId", userId);
}
}
I have also set render-mode to server in _Host.cshtml to handle prerendering as said in the docs:
@page "/"
@using Microsoft.AspNetCore.Components.Web
@namespace UserApplication.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<base href="~/" />
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />
<link href="css/site.css" rel="stylesheet" />
<link href="UserApplication.styles.css" rel="stylesheet" />
<link rel="icon" type="image/png" href="favicon.png"/>
<component type="typeof(HeadOutlet)" render-mode="ServerPrerendered" />
</head>
<body>
<component type="typeof(App)" render-mode="Server" />
<div id="blazor-error-ui">
<environment include="Staging,Production">
An error has occurred. This application may no longer respond until reloaded.
</environment>
<environment include="Development">
An unhandled exception has occurred. See browser dev tools for details.
</environment>
<a href="" class="reload">Reload</a>
<a class="dismiss"></a>
</div>
<script src="_framework/blazor.server.js"></script>
</body>
</html>
Finally I have used the state provider in the child component:
<h3>ShowData</h3>
@page "/showdata"
<h1>@StateProvider?.userId</h1>
@code {
[CascadingParameter]
private StateProvider? StateProvider { get; set; }
}
No error occurs but the userId value is shown as zero here. It is perfectly set in the browser when I login, but it does not get fetched properly.
I would really appreciate if someone can help me with this. Thanks.