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
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.
An Addendum to the answer by @HenkHolterman.
A refactored better version of your code.
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:
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.