|
| 1 | +// id: async-fetch-list |
| 2 | +// intent: fetch async data with UseResource and render loading, error, and reloading states |
| 3 | +#:package Microsoft.UI.Reactor@0.0.0-local |
| 4 | +#:property Platform=ARM64 |
| 5 | + |
| 6 | +using System; |
| 7 | +using System.Collections.Generic; |
| 8 | +using System.Linq; |
| 9 | +using System.Threading; |
| 10 | +using System.Threading.Tasks; |
| 11 | +using Microsoft.UI.Reactor; |
| 12 | +using Microsoft.UI.Reactor.Core; |
| 13 | +using Microsoft.UI.Xaml.Controls; |
| 14 | +using static Microsoft.UI.Reactor.Factories; |
| 15 | + |
| 16 | +ReactorApp.Run<App>("Async Fetch List", width: 560, height: 520); |
| 17 | + |
| 18 | +record Repo(int Id, string Name, string Description); |
| 19 | + |
| 20 | +static class Api |
| 21 | +{ |
| 22 | + public static async Task<IReadOnlyList<Repo>> ListReposAsync(string owner, CancellationToken cancellationToken) |
| 23 | + { |
| 24 | + await Task.Delay(800, cancellationToken); |
| 25 | + if (owner == "fail") |
| 26 | + { |
| 27 | + throw new InvalidOperationException("Owner not found"); |
| 28 | + } |
| 29 | + |
| 30 | + return |
| 31 | + [ |
| 32 | + new(1, $"{owner}/alpha", "first repo"), |
| 33 | + new(2, $"{owner}/beta", "second repo"), |
| 34 | + new(3, $"{owner}/gamma", "third repo") |
| 35 | + ]; |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +class App : Component |
| 40 | +{ |
| 41 | + public override Element Render() |
| 42 | + { |
| 43 | + var (owner, setOwner) = UseState("microsoft"); |
| 44 | + var repos = UseResource(cancellationToken => Api.ListReposAsync(owner, cancellationToken), deps: [owner]); |
| 45 | + |
| 46 | + return VStack(12, |
| 47 | + TextField(owner, setOwner, placeholder: "GitHub owner"), |
| 48 | + Caption("Try \"fail\" to see the error state."), |
| 49 | + repos.Match<Element>( |
| 50 | + loading: () => HStack(8, |
| 51 | + ProgressRing().IsActive(true).Width(20).Height(20), |
| 52 | + TextBlock("Loading…")), |
| 53 | + data: list => VStack(8, |
| 54 | + list.Select(repo => |
| 55 | + Border( |
| 56 | + VStack(2, |
| 57 | + TextBlock(repo.Name).Bold(), |
| 58 | + Caption(repo.Description))) |
| 59 | + .Padding(12) |
| 60 | + .CornerRadius(6) |
| 61 | + .WithKey(repo.Id.ToString()) |
| 62 | + ).ToArray<Element?>()), |
| 63 | + error: ex => InfoBar("Error", ex.Message).Severity(InfoBarSeverity.Error), |
| 64 | + reloading: previous => VStack(8, |
| 65 | + HStack(8, |
| 66 | + ProgressRing().IsActive(true).Width(20).Height(20), |
| 67 | + TextBlock("Refreshing…")), |
| 68 | + VStack(8, |
| 69 | + previous.Select(repo => |
| 70 | + TextBlock(repo.Name) |
| 71 | + .Opacity(0.5) |
| 72 | + .WithKey(repo.Id.ToString())) |
| 73 | + .ToArray<Element?>())))) |
| 74 | + .Padding(24); |
| 75 | + } |
| 76 | +} |
0 commit comments