diff --git a/Radzen.Blazor/RadzenAsyncLoader.razor b/Radzen.Blazor/RadzenAsyncLoader.razor new file mode 100644 index 00000000000..49919b7b9e6 --- /dev/null +++ b/Radzen.Blazor/RadzenAsyncLoader.razor @@ -0,0 +1,10 @@ +@typeparam TData + +@if (IsLoading && LoadingTemplate != null) +{ + @LoadingTemplate +} +else if (Result != null) +{ + @Template(Result) +} \ No newline at end of file diff --git a/Radzen.Blazor/RadzenAsyncLoader.razor.cs b/Radzen.Blazor/RadzenAsyncLoader.razor.cs new file mode 100644 index 00000000000..ffe8e7f29f7 --- /dev/null +++ b/Radzen.Blazor/RadzenAsyncLoader.razor.cs @@ -0,0 +1,73 @@ +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Rendering; +using System; +using System.Threading.Tasks; + +namespace Radzen.Blazor +{ + /// + /// A generic component for asynchronously loading data and rendering templates based on the loading state. + /// + public partial class RadzenAsyncLoader : ComponentBase + { + /// + /// The template to render when data is loaded. + /// + [Parameter] + public RenderFragment Template { get; set; } + + /// + /// The template to render while data is loading. + /// + [Parameter] + public RenderFragment LoadingTemplate { get; set; } + + /// + /// The asynchronous task that fetches the data. + /// + [Parameter] + public Task DataTask { get; set; } + + /// + /// A callback action invoked when an error occurs during data loading. + /// + [Parameter] + public Action OnError { get; set; } + + /// + /// Indicates whether the component is in a loading state. + /// + private bool IsLoading { get; set; } = true; + + /// + /// The loaded data result. + /// + private TData Result { get; set; } + + /// + /// Initializes the component and asynchronously loads data. + /// + /// A representing the asynchronous operation. + protected override async Task OnInitializedAsync() + { + try + { + Result = await DataTask; + IsLoading = false; + } + catch (Exception ex) + { + IsLoading = false; + if (OnError != null) + { + OnError(ex); + } + } + finally + { + // Ensure UI updates after loading completes or encounters an error. + StateHasChanged(); + } + } + } +} diff --git a/Radzen.DocFX/guides/components/asyncloader.md b/Radzen.DocFX/guides/components/asyncloader.md new file mode 100644 index 00000000000..a3d5f19856d --- /dev/null +++ b/Radzen.DocFX/guides/components/asyncloader.md @@ -0,0 +1,21 @@ +# AsyncLoader component +This article demonstrates how to use the AsyncLoader component. + +# Loading data asynchronously +The AsyncLoader component enables loading data asynchronously in Blazor applications. It offers the flexibility to specify loading and loaded templates, handle errors during data retrieval, and update the UI accordingly. + +``` + + + + + + +``` \ No newline at end of file