skip to Main Content

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.

3

Answers


  1. It will of course work. OnInitialized() is just another method.

    But it is very bad style, and completely unnecessary. Use OnInitialized() for one-time initialization and write a GetData() method to get data.

    Login or Signup to reply.
  2. 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();
        }
    }
    
    Login or Signup to reply.
  3. If I am understanding the purpose of the code correctly, You want to display the initial value of LastDate, and to be able to update it by hitting the button.

    Here is one way to do it:

     private string? LastDate { get; set; }
    
     protected override void OnInitialized()
     {
         LastDate = lcService.GetLastDate(Uid);  
     }
    
     void SetLastDate()
     { 
        lcService.SetDate(Uid)
        LastDate = lcService.GetLastDate(Uid);
        StateHasChanged(); //Depends on the case, not required
     }
    

    By Design, the OnInitialized is (and must be) used exclusively to initialize a component for the entire lifetime of the component instance.

    In your use-case, OnInitialized serves one purpose which is to get a string value from a given service. In a more complex scenario, calling it manually can dramatically affect how your component should behave.

    Another possible way here is to two-way bind your LastDate field there would be no need to call your service again.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search