'Setting the global state only once using Fluxor in Hosted Blazor WASM app
I have a .NET 5.0 Hosted Blazor WASM app that looks like this:
I am using scaffolded Identity razor pages in server project for sign in and sign up etc.
I want to store the logged in User
object inside the global state of the Blazor Client WASM app. This object contains user profile information and some other data. The idea is to avoid fetching this information from database again and again as data from this object is displayed on a few other pages.
For this purpose, I am using Blazor.Fluxor.Web
. In order to store this object as global state, I am calling the Dispatch
method in Navbar document.
@using IdentityDocApp.Client.Store.User;
@inject IDispatcher Dispatcher
@inject IState<UserState> UserState
<ul class="nav flex-column">
<li class="nav-item px-3">
<NavLink class="nav-link" href="" Match="NavLinkMatch.All">
<span class="oi oi-home" aria-hidden="true"></span> Home
</NavLink>
</li>
<AuthorizeView Roles="@IdentityDocApp.Shared.RoleTypes.ADMIN">
<li class="nav-item px-3">
<NavLink class="nav-link" href="journals">
<span class="oi oi-book" aria-hidden="true"></span> Journal Entry
</NavLink>
</li>
</AuthorizeView>
</ul>
@code {
[CascadingParameter] public Task<AuthenticationState> AuthTask { get; set; }
private System.Security.Claims.ClaimsPrincipal user;
protected async override Task OnInitializedAsync()
{
var authState = await AuthTask;
this.user = authState.User;
Dispatcher.Dispatch(new LoadUserAction(user.Identity.Name));
}
}
As per my understanding of SPAs, a component would only be re-rendered if it has been changed. Now NavBar
is not changing at all, still as soon as I route towards /journals
page from /
index page, the Navbar
gets rerendered and the state is populated again from the db.
Everytime I visit a page, the whole process of calling the db to fetch the state repeats.
Question. 1) Why? I want to re-fetch the state as per my choice.
Question. 2) How should I populate this global state so that it is only filled in once (right after the user logs in) and not again and again?
Update
I am using Cosmos DB and I am seeking to keep the document/item of the logged-in user inside the state. This document contains multiple entities that are owned by/embedded in the user document. Hence I do not want to store it all in claims. The main idea behind the global state approach is to save query RU costs.
Solution 1:[1]
For your scenario, it is enough to check the AuthTask.Value.Loaded value before dispatching the LoadUserAction. Therefore results are queried only for the first time
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |