Search code examples
routesblazorlifecycleblazor-webassemblyroute-parameters

Blazor: Forcing Component/Page Life-cycle


I'm building an application using Blazor Web-assembly and I want the user to be able to load the application via a route, e.g.

http://www.someapp.com/{Page}/{Item}

If the user selects the above route it should go to {Page} and display {item}.
This works out-of-the-box; however, if the user applies the following steps:

  1. In the browser, Copy + Paste http://www.someapp.com/Inventory/1 //works
    a. SetParametersAsync (fired)
    b. OnSetParameters (fired)
  2. NEXT, change URL to http://www.someapp.com/Inventory/2 //Doesn't work
    a. SetParametersAsync (not fired)
    b. OnSetParameters (not fired)

If the {Page} is the same, the components' lifecycle doesn't kick-off even if the route parameter changed. What gives? Is there a way to force it?

Environment: VS2019
.NET CORE: v3.1


Solution

  • Here's some code (based on the Counter component), copy and test it. See for yourself that both methods are executed when you change the parameter value.

    Incidentally, it's OnParametersSet, not

    OnSetParameters (not fired)

    @page "/counter/{MyCount:int}"
    
    <h1>Counter</h1>
    
    <p>Current count: @currentCount</p>
    
    <button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
    
    @code {
        private int currentCount = 0;
        [Parameter]
        public int MyCount { get; set; }
    
        protected override void OnParametersSet()
        {
            Console.WriteLine("OnParametersSet");
        }
    
        public override async Task SetParametersAsync(ParameterView parameters)
        {
            Console.WriteLine("SetParametersAsync");
            await base.SetParametersAsync(parameters);
        }
    
        private void IncrementCount()
        {
            currentCount++;
        }
    }
    

    Note: Since Blazor reuses the Page ( currently Counter) with varying parameter; that is, it does not re-create the Page object. That is why life cycle methods such as the OnInitialized[Async) pair run only once, when the component is born.