UNRE
UNRE

Reputation: 79

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.

Upvotes: 0

Views: 64

Answers (3)

MrC aka Shaun Curtis
MrC aka Shaun Curtis

Reputation: 30310

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();
    }
}

Upvotes: 1

mrSoh
mrSoh

Reputation: 308

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.

Upvotes: 1

Henk Holterman
Henk Holterman

Reputation: 273621

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.

Upvotes: 1

Related Questions