Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Should I be using SetParametersAsync() for all [Parameter] properties?

I am now using SetParametersAsync() for a [Parameter] that is not set when OnInitializedAsync() is called. But that led to my thinking…

Even a property as simple as Visible, while usually set to "true" or "false" could sometimes be set based on a DB query and therefore get set after OnInitializedAsync() is called.

So… should I handle every [Parameter] only in SetParametersAsync() and not in OnInitializedAsync()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Or, should I handle them in OnInitializedAsync() if they’re non-null and also watch for them being changed in SetParametersAsync()

And associated question. For each parameter I handle in SetParametersAsync(), do I need to keep a local copy of what it was last set to, to determine if the new value is a change? Or is there a way I can ask ParameterView if the value is changed? (I can’t find anything in my searching.)

This is a difficult question (did it change) as in this case, it’s a List and so getting a "new value where list.Count == prevList.Count does not mean that the list didn’t change.

>Solution :

I use the following rule of thumb:

OnInitialized-:

Here I will get things ready for the component, and very rarely do anything related to component parameters. Very often I will set internal or private parameters/fields for UI based logic or other defaults not set on the parameter/field. Things like rendering of a loading modal, EditContext etc. If I have a component that does not have parameters, I will add all starting logic here.

OnParameterSet-:

Here I will add all my component parameter logic and do hash checking to identify whether a parameter updated. Useful when working with your List<T> example and it’s much cheaper storing a hash string instead of a whole list.

OnAfterRender-:

I usually reserve this for JavaScript. In my ~4 years of Blazor, I’ve only called JavaScript here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading