Reputation: 48686
So I have a Blazor application in which a user logs in and the header component changes depending on whether a user is logged in or not. After the use logs in, they are redirected to the main home page, but the header component does not update unless I hit the refresh button on the browser. I tried using StateHasChanged()
. Here is my relevant code in the header component:
@using Newtonsoft.Json
@inject IJSRuntime JsRuntime
@inject NavigationManager NavManager
@if (!string.IsNullOrWhiteSpace(FirstName))
{
<div class="header-user-widget">
<button class="btn btn-cart">
Cart <span class="badge badge-cart">@CartCount</span>
</button>
<i class="fa fa-user-circle"></i> @FirstName @LastName
<i class="fa fa-sign-out-alt header-sign-out" @onclick="SignOutClicked"></i>
</div>
}
@code {
private string FirstName { get; set; }
private string LastName { get; set; }
private int CartCount { get; set; }
protected override async Task OnInitializedAsync()
{
var page = NavManager.ToBaseRelativePath(NavManager.Uri).ToLower();
var cookie = await JsRuntime.InvokeAsync<string>("Cookies.get", "Login");
if (!page.StartsWith("login"))
{
if (string.IsNullOrWhiteSpace(cookie))
{
NavManager.NavigateTo("/Login");
return;
}
}
if (!string.IsNullOrWhiteSpace(cookie))
{
var decodedCookie = cookie.FromBase64String();
FirstName = CookieHelper.GetValueFromKey(decodedCookie, "FirstName");
LastName = CookieHelper.GetValueFromKey(decodedCookie, "LastName");
}
CartCount = await NumberOfItemsInCart();
}
}
And here is my login page:
@page "/login"
@inject IJSRuntime JsRuntime
@inject NavigationManager NavManager
<LoginBox OnLoginButtonClick="@LoginButtonClicked" />
@code {
private async Task LoginButtonClicked(LoginBoxReturnModel model)
{
var cookieString = $"UserId={model.UserId}|FirstName={model.FirstName}|LastName={model.LastName}|Email={model.EmailAddress}|IsAdmin={model.IsAdmin}";
var encyptedString = cookieString.ToEncryptedBase64String();
await JsRuntime.InvokeVoidAsync("Cookies.set", "Login", encyptedString);
StateHasChanged(); // This line doesn't seem to have any effect
NavManager.NavigateTo("/");
}
}
Once the user logs in, they are properly redirected to "/"
page, but the header is not updated. If I hit F5 in the browser to refresh it, then the header is correct. I feel like what is going on is that the application is navigating before the StateHasChanged()
line has any time to refresh, thus it is never refreshing. If this is the case, how should I be implementing this?
Upvotes: 4
Views: 2198
Reputation: 14523
Drop the StateHasChanged(), your navigating from "/login" to "/". The true should force the load of the cookie like f5 is doing.
NavManager.NavigateTo("/",true);
Upvotes: 4