I have a Razor page that needs to show my transactions and load it from database but. When I visit the page for the first time, everything works fine, but when I refresh the page, all the data stops loading. I'm a beginner and I don't know what it could be. Here is my code
@page "/home"
@rendermode InteractiveServer
@using FinanceTracker.Components.Data
@using FinanceTracker.Services
@inject UserService UserService
@inject TransactionService TransactionService
@inject CustomAuthStateProvider AuthStateProvider
@inject NavigationManager Navigation
<PageTitle>Dashboard</PageTitle>
<header class="header">
<h1 class="page-title">Dashboard</h1>
<div class="logout">
<button @onclick="Logout" class="logout-btn">Logout</button>
</div>
</header>
<main class="main">
@if (transactions != null)
{
<div class="transaction-balance">
<p class="transaction-balance-text">Cash</p>
<p class="transaction-balance-amount">@GetTotalAmount()</p>
</div>
}
<div class="transaction-list">
@if (transactions != null)
{
<h2 class="transaction-heading">Last Transaction</h2>
@foreach (var transaction in transactions)
{
<div class="transaction-item">
<div class="transaction-item-content">
@if (transaction.Type == "Receive")
{
<p class="transaction-item-amount green">[email protected] UAH</p>
}
else
{
<p class="transaction-item-amount">@transaction.Amount UAH</p>
}
<p class="transaction-item-description">@transaction.Description</p>
</div>
<img @onclick="() => DeleteTransaction(transaction.Id)" class="transaction-item-btn" src="Delete-button.svg.png"/>
</div>
}
}
else
{
<p>Loading...</p>
}
</div>
<button class="btn btn-primary" @onclick="ShowModal">Add Transaction</button>
</main>
<AddTransactionModal Visible="@showModal" />
@code{
private List<Transaction> transactions;
public bool showModal = false;
protected override async Task OnInitializedAsync()
{
var authState = await AuthStateProvider.GetAuthenticationStateAsync();
var login = authState.User.Identity.Name;
if (login != null)
{
var user = await UserService.GetUserByLogin(login);
if (user != null)
{
var userId = user.Id;
await LoadTransactions(userId);
}
}
}
private async Task LoadTransactions(int userId)
{
transactions = await TransactionService.GetTransactionsByUserId(userId);
}
I tried to debug my code, but I didn't see anything that could help me
PROBLEM SOLVED
The problem was with my CustomAuthenticationState
Service
The issue with the SetUser
and GetAuthenticationStateAsync
methods not retaining the user information across different pages likely stems from the CustomAuthStateProvider
not persisting the user state. In a Blazor
Server application, the authentication state is not retained across page reloads by default, and you need to implement a more persistent storage mechanism like session storage
or cookies
.
I added session storage and everything works now