'Blazor component availability moment
NOTE: In this question I make use of a specific component, but I guess my issue is related to my general approach to blazor pages rather than this specific component.
I have a Blazor WebAssembly app with the following page:
page.razor
@page "/mypage"
<h3>Title</h3>
<BlazorSlickCarousel @ref="carVp" Configurations="carVpConf">
<BlazorSlickCarouselContent>
</BlazorSlickCarouselContent>
<BlazorSlickCarouselLoading>
</BlazorSlickCarouselLoading>
</BlazorSlickCarousel>
page.razor.cs
using WMBlazorSlickCarousel.WMBSC;
private BlazorSlickCarousel carVp;
private WMBSCInitialSettings carVpConf;
private bool cond = true;
protected override void OnInitialized()
{
carVpConf = new WMBSCInitialSettings(){ /* some options */ };
}
protected override async Task OnParametersSetAsync()
{
if (cond)
{
/* do nothing */
}
else
{
/* await time consuming task */
}
await PopulateCarousel();
}
public async Task PopulateCarousel()
{
var div = $@"<div class='vs-container'>Some stuff</div>";
for(int i = 1; i <= 3; i++)
{
await carVp.Add(div);
}
}
If cond == true, PopulateCarousel() behaviour is unpredictable: sometimes an ArgumentNullException is thrown, sometimes not all divs are added to the carousel.
If cond == false, everything is working.
I guess that when cond == true the carVp component is not yet (fully) created/initialized.
In fact, if I add a little delay to the first If branch (with await Task.Run(() => Task.Delay(1000)); everything is fine.
The question is: where should I put my call to PopulateCarousel() to be sure that the component is fully created and initialized? Is there a (generic) way to check for component state?
I tried with OnInitializedAsync, OnAfterRenderAsync and OnAfterRender, but none of them worked.
Thank you!
Solution 1:[1]
The component life cycle events are fired in following sequence
OnInitialized ----->OnParametersSet----->OnAfterRender
As you said "to be sure that the component is fully created and initialized?". OnAfterRender event is fired when component UI is fully rendered and is available for access and updates.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Surinder Singh |
