Mohammed Gamal
Mohammed Gamal

Reputation: 3

i have a blazor app for factory layout and i want to make the functionality of reloading every 15 seconds but it doesn't work

i've tried PeriodicTimer and jsinterop but both doesn't achieve the desired behaviour

here's my @code block that outputs no errors, exception nor the expected bahaviour

@code {
public List<Station> Stations = new List<Station>();
private List<Connection> Connections = new List<Connection>();
private List<CurvedConnection> CurvedConnections = new List<CurvedConnection>();
private List<string> LineElements = new List<string>();
private PeriodicTimer periodicTimer;
private CancellationTokenSource _cts = new CancellationTokenSource();
private DateTime currentTime = DateTime.Now;
private bool isInitialized = false;


protected override void OnInitialized()
{
    SetupInitialStations();
    UpdateConnections();
}

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        isInitialized = true;
        periodicTimer = new PeriodicTimer(TimeSpan.FromSeconds(15));

        while (await periodicTimer.WaitForNextTickAsync(_cts.Token))
        {
            await JS.InvokeVoidAsync("reloadPage");
            await JS.InvokeVoidAsync("console.log", "Periodic work done", currentTime);
        }
    }

public void Dispose()
{
    _cts.Cancel();
    periodicTimer?.Dispose();
}}

Upvotes: 0

Views: 51

Answers (1)

gbrooksman
gbrooksman

Reputation: 115

what i do in this case is navigate to an empty page passing a parameter of the razor page name to go back to. This triggers the reload of a page. So inject the Navigation Manager at the top of the page :

@inject NavigationManager nav;

then in your code where you want the reload to happen:

 nav.NavigateTo("/EmptyPage?firstPage");

EmptyPage.razor is only this:

 @page "/EmptyPage/{GoToPage}"
 @inject NavigationManager nav;

    @code
    {
        [Parameter] public string GoToPage { get; set; }
    
        protected override void OnInitialized()
        {
            base.OnInitialized();
    
            nav.NavigateTo($"/{GoToPage}");
        }
    
    }

see this issue: [https://stackoverflow.com/questions/70539158/refresh-blazor-page]

Upvotes: 0

Related Questions