Reputation: 23
I need to have a value available to all pages in my Blazor server side application (An AccountID). Obviously any page variable or global variable is reset/lost on page refresh.
I looked at all the various options in terms of cookies, local storage and session storage and it looks like the best fit would be the use of cookies with Javascript Interop.
Is this the best way and what is the best way to implement this?
Upvotes: 1
Views: 1611
Reputation: 170257
I'd not mess with JS-interop if there is no real need to (which there isn't in your case). There are many 3rd party packages that can help. Blazored.LocalStorage for example.
.csproj
:<PackageReference Include="Blazored.LocalStorage" Version="4.2.0" />
ConfigureServices
:public void ConfigureServices(IServiceCollection services)
{
services.AddBlazoredLocalStorage();
}
@inject Blazored.LocalStorage.ILocalStorageService localStorage
@code {
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await localStorage.SetItemAsync("name", "Darren");
var name = await localStorage.GetItemAsync<string>("name");
}
}
And if you're using dotnet 5 or up, have a look at this: https://learn.microsoft.com/en-us/aspnet/core/blazor/state-management?view=aspnetcore-6.0&pivots=server#save-and-load-data-within-a-component
Upvotes: 1