asp.netblazorblazor-server-side

Blazor components and OnInitialized() inside another method


I have Blazor component with button. Clicking the button calls the method SetLastDate().

 private string? LastDate { get; set; }

 protected override void OnInitialized()
 {
     LastDate = lcService.GetLastDate(Uid);  
 }

 void SetLastDate()
 { 
    lcService.SetDate(Uid)
    OnInitialized(); 
 }

Everything is working. But how correct is it to call the OnInitialized() method inside another method If I need to update the UI with new values and styles?

Do this inside the OnParametersSet method, but the point is that no parameters are changed (im just clicking the button with void func) and this method is not invoked.


Solution

  • An Addendum to the answer by @HenkHolterman.

    A refactored better version of your code.

    @page "/"
    @inject LcService lcService
    
    <PageTitle>Home</PageTitle>
    
    <h1>Hello, world!</h1>
    
    Welcome to your new app.
    
    <div class="alert alert-info m-2">Last Date : @_lastDate</div>
    
    <div class="m-2 ">
        <button class="btn btn-primary" @onclick="this.SetLastDate" >Update</button>
    </div>
    
    @code {
        private string? _lastDate { get; set; }
        private Guid _uid = Guid.NewGuid();
    
        protected override void OnInitialized()
        {
            this.GetLastDate();
        }
    
        private void GetLastDate()
        {
            _lastDate = this.lcService.GetLastDate(_uid);
        }
    
        private void SetLastDate()
        {
            this.lcService.SetDate(_uid);
            this.GetLastDate();
        }
    }