Reputation: 1566
Given a Razor Component to display an object details, what is the best pratice to get that object from DB?
I my case I always set the object using OnInitializedAsync like follows:
private ProductModel productModel; > protected override async Task OnInitializedAsync() { productModel = await _productsService.GetObjectDetails(Id); }
I wonder if Im doing the best way in terms of performance or is there a better way, for example using OnParametersSet...
Thank you
Upvotes: 1
Views: 3267
Reputation: 45586
First off, the OnInitialized{Async}
method pair are called before the OnParametersSet{Async}
method pair. The main difference between these pairs is that the first is called only once, when the component is created and initialized.
OnParametersSet{Async}
method pair, however, is called:
After the component is initialized in OnInitialized
or OnInitializedAsync
. And at each subsequent re-rendering of the parent component, when a primitive parameter has changed, as for instance, ID (which is defined as a component parameter property), and if you also have complex-typed parameters defined in your component.
What you do is correct. But if you do that in OnParametersSet{Async}
method pair, it would make no difference whatsoever...It would incur no overhead.
The good pattern is to use OnInitialized{Async}
method pair, and if say, you want to call the same method (_productsService.GetObjectDetails
) you call from OnInitialized{Async}, with a changed parameter value, you may call it from OnParametersSet{Async} method pair
, depending on your general design.
Are you confused because of the SetParametersAsync
method ? This is something entirely different than the OnParametersSet{Async} method pair
, though related.
I understud that OnParametersSet is mainly to use when parent component is passing parameters, SetParametersAsync I dont know any about it..
The SetParametersAsync
method is not really considered a life cycle method. SetParametersAsync
is executed before the OnInitialized{Async}
method pair. You can inspect this code to see what is going on... The role of the SetParametersAsync
method is to set parameters supplied by the component's parent in the render tree or from route parameters. You may override it if you need, but usually you won't, depending on what you do.
Upvotes: 2
Reputation: 273179
in terms of performance
There will be very little diference. Don't bother. Your current code is fine.
for example using OnParametersSet...
If that Id
is a parameter that can change then OnParametersSet is the only correct place.
Upvotes: 2