Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4263

Blazor - Navigation during the Blazor `OnInitialized" lifecycle method causes unexpected behavior

$
0
0

For context I am using Blazor in .NET 8 (8.0.3) with interactive server-side rendering.

I have a scenario where during initialization of a page component (source page), I want to redirect to a different page (target page). On the target page I want to read a query parameter during initialization.

The problem that arises is the target page's OnInitialized method now runs twice. First, with the correct state, then a second time with what appears to be a stale state (from the previous page). The second run will reset all the properties and have the URI of the previous page which resets the query params accessed with [SupplyParameterFromQuery].

This is a simplified example to re-create:

@page "/page1"<div></div>@code {    protected override async Task OnInitializedAsync() {        if (shouldRedirect == true)        {            NavigationManager.NavigateTo("/page2");        }    }}
@page "/page2"@if (_isWelcomeMessageVisible){<span>Welcome!</span>}@code {    [Parameter]    [SupplyParameterFromQuery]    public bool IsFirstVisit { get; set; }    private bool _isWelcomeMessageVisible { get; set; }    protected override async Task OnInitializedAsync() {        Console.WriteLine("uri: " + NavigationManager.Uri);        if (IsFirstVisit)        {            _isWelcomeMessageVisible = true;        }    }}

The console output from initialization of page2 will be:

uri: http://127.0.0.1:5045/page2?IsFirstVisit=trueuri: http://127.0.0.1:5045/page1

In this case the welcome message will be visible for a split-second between runs.

I am looking for a solution or workaround to redirect during page initialization without seeing a brief blank page. Any ideas?


Viewing all articles
Browse latest Browse all 4263

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>