简体   繁体   中英

Loading data on component load

One would think this is an easy task. But how do I call a service method on component load without it firing twice?

Currently -

protected override async Task OnInitializedAsync()
{
   await Initialize(); 
}

private async Task Initialize()
{
    Video = await _VideoService.GetAsync(Id);
}

Right now this gets called twice, which doens't seem like a good idea to hit the database twice for the same information.

I've tried just having this below, but it will throw an error before it even renders everytime.

protected override async Task OnAfterRenderAsync(bool firstRender)
{
  if(firstRender)
  { 
    await Initialize();
  }
}

OnInitializedAsync lifecycle method for initializing the component is executed twice :

  1. When the component is prerendered statically.
  2. After the server connection has been established.

It is by design - check Stateful reconnection after prerendering and other sections of this article to figure out what would be the safe way to load data in your case. Maybe it is SetParametersAsync or OnParametersSetAsync

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM