C#C
C#2y ago
Daryl

Blazor Pages rendering before async methods finish, breaking the page?

The below code is crashing my app because applicationUser is null when it's referenced in the HTML. This is a common issue I keep facing, how are you meant to handle it?

    protected override async Task OnInitializedAsync()
    {
        while(userId == null)
        {
            var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
            var user = authState.User;
            userId = user.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        }

        transactions = DataService.GetAllTransactions(userId);
        mostExpensiveTransactions = transactions.OrderByDescending(t => t.Amount).Take(5).ToList();

        while(applicationUser == null)
        {
            applicationUser = await UserManager.FindByIdAsync(userId);
        }
    }


I thought the while loop would ensure that it can never continue but I guess it continues because it's returning a Task?

ChatGPT suggests I added a Delay of 200ms after the command but it doesn't really feel like it would guarantee the issue is solved.

Thanks!
Was this page helpful?