Razor component - Load and display data asynchronously

1.9k Views Asked by At

I have a Razor component displaying a list of articles and I would like to load each article's image asynchronously after the page was rendered, so that the user would see the images poping on the page one after another.

The problem is, where and how shoud I make these calls ?

The HTML:

@foreach (Article article in articles)
{
   <div>
      <p>@article.name</p>
      if (article.image != null) 
      {
         <img src="data:image/jpg;base64,@article.image">
      }
   </div>
}

The code:

List<Article> articles = new List<Article>();
protected override async Task OnInitializedAsync()
{
    articles = LoadArticles(); //Asume this function initialises the article list
}

async Task LoadPicture(Article article)
{
    await article.LoadImage(); //This will make the server call to get the base64 of the image
}

I would need to call the LoadPicture function for each of my article in the page but I would like to make asynchronously without having to wait for all of the calls to refresh the whole page.

How should I proceed ?

1

There are 1 best solutions below

0
On

Here is a rough example of what I described you could do in my comment and it should achieve the behaviour you originally wanted.

Doing it this way means that each Article component takes care of itself and when it should be rendered or updated, and each api call to fetch the image data should be independant.

-- Article List Component

@foreach(var article in Articles)
{
    <Article Model="article">
}


@code {

    List<Article> Articles {get;set;}

    protected override Task OnInitializedAsync()
    {
        return LoadArticlesAsync(); //Api call to get all articles list and which sets Articles.
    }


}

-- Article.razor component

@if (Model != null)
{
    <h1> @Model.Title </h1>

    @if (_imageLoaded)
    {
        <img src="@ImageBase64"/>
    }
}

@code
 {
    [Parameter]
    public Article Model {get;set;}

    private bool _imageLoaded = false;
    private string ImageBase64 {get;set;}

    protected override async Task OnInitializedAsync()
    {
        ImageBase64 = await LoadArticleImage();
        _imageLoaded = true;
    }
}