{"slug":"fetch-and-send-data","title":"fetch-and-send-data","summary":"Call APIs, load data into components, and handle the async lifecycle in Blazor. USE FOR fetching data from a backend, submitting data to an API, displaying loading/error states, registering HttpClient, building service abstractions for Auto/WebAssembly render modes. DO NOT USE fo","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-08-24T05:37:37.188559Z","repo":{"url":"https://github.com/dotnet/skills","stars":6296,"forks":500,"license":"MIT","updatedAt":"2026-11-19T18:23:42Z"},"bodyHtml":"<hr>\n<h2>license: MIT\nname: fetch-and-send-data\ndescription: Call APIs, load data into components, and handle the async lifecycle in Blazor. USE FOR fetching data from a backend, submitting data to an API, displaying loading/error states, registering HttpClient, building service abstractions for Auto/WebAssembly render modes. DO NOT USE for form validation (see collect-user-input), prerendering persistence (see support-prerendering), or project scaffolding (see create-blazor-project).</h2>\n<h1>Fetch and Send Data</h1>\n<h2>Step 1 — Read AGENTS.md</h2>\n<p>Check <strong>Interactivity Mode</strong> and <strong>Scope</strong>:</p>\n<table>\n<thead>\n<tr>\n<th>Mode</th>\n<th>Data access</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>None (Static SSR)</td>\n<td>Server-side: inject services/<code>DbContext</code>. Use <code>[StreamRendering]</code> for loading UX.</td>\n</tr>\n<tr>\n<td>Server</td>\n<td>Server-side: inject services/<code>DbContext</code>. Guard prerender with <code>??=</code> + <code>[PersistentState]</code>.</td>\n</tr>\n<tr>\n<td>WebAssembly</td>\n<td>Browser-side: <code>HttpClient</code> only. No direct server access.</td>\n</tr>\n<tr>\n<td>Auto</td>\n<td>Both server and browser. Always go through an API.</td>\n</tr>\n</tbody>\n</table>\n<h2>Step 2 — Register HttpClient</h2>\n<p>Only needed when calling external APIs from Server, or always for WebAssembly/Auto. Server components accessing their own database should inject <code>DbContext</code> or a service directly.</p>\n<pre><code>// Named client — requires Microsoft.Extensions.Http NuGet\nbuilder.Services.AddHttpClient(\"CatalogAPI\", client =&gt;\n{\n    client.BaseAddress = new Uri(\"https://api.example.com/\");\n});\n\n// Typed client\nbuilder.Services.AddHttpClient&lt;CatalogClient&gt;(client =&gt;\n    client.BaseAddress = new Uri(\"https://api.example.com/\"));\n</code></pre>\n<p>For WebAssembly/Auto with prerendering, register in <strong>both</strong> server and <code>.Client</code> <code>Program.cs</code>.</p>\n<h2>Step 3 — Fetch Data</h2>\n<h3>Simple load</h3>\n<pre><code>@page \"/products\"\n@inject CatalogClient Catalog\n\n@if (products is null)\n{\n    &lt;p&gt;Loading…&lt;/p&gt;\n}\nelse\n{\n    @foreach (var p in products)\n    {\n        &lt;p&gt;@p.Name — @p.Price.ToString(\"C\")&lt;/p&gt;\n    }\n}\n\n@code {\n    private Product[]? products;\n\n    protected override async Task OnInitializedAsync()\n    {\n        products = await Catalog.GetProductsAsync();\n    }\n}\n</code></pre>\n<p>No error handling needed in the simplest case — wrap the component usage in <code>&lt;ErrorBoundary&gt;</code> at the parent/layout level to catch unhandled exceptions.</p>\n<h3>Static SSR — StreamRendering</h3>\n<p>Without <code>[StreamRendering]</code>, the user sees nothing until <code>OnInitializedAsync</code> completes:</p>\n<pre><code>@attribute [StreamRendering]\n</code></pre>\n<p>Only affects Static SSR. No effect on interactive components.</p>\n<h3>Prerendering guard</h3>\n<p>Prerendering calls <code>OnInitializedAsync</code> twice. Skip the duplicate:</p>\n<pre><code>[PersistentState] private Product[]? products;\n\nprotected override async Task OnInitializedAsync()\n{\n    products ??= await Catalog.GetProductsAsync();\n}\n</code></pre>\n<p>See the <code>support-prerendering</code> skill for details.</p>\n<h2>Step 4 — Handle Errors</h2>\n<p>Use <code>&lt;ErrorBoundary&gt;</code> as the default error strategy. It provides a consistent error experience across all components without any per-component catch logic. Wrap component usage at the layout or parent level:</p>\n<pre><code>&lt;ErrorBoundary&gt;\n    &lt;ChildContent&gt;\n        &lt;ProductList /&gt;\n    &lt;/ChildContent&gt;\n    &lt;ErrorContent&gt;\n        &lt;div class=\"alert alert-danger\"&gt;Something went wrong. Please refresh.&lt;/div&gt;\n    &lt;/ErrorContent&gt;\n&lt;/ErrorBoundary&gt;\n</code></pre>\n<p>Non-cancellation exceptions (<code>HttpRequestException</code>, etc.) propagate to <code>ErrorBoundary</code> automatically — no catch blocks needed in the component.</p>\n<h3>Cancellation is special</h3>\n<p><code>ComponentBase</code> silently swallows <strong>all</strong> <code>OperationCanceledException</code> — both self-initiated (disposal, parameter change) and external (HttpClient timeout). <code>ErrorBoundary</code> never sees them. This means:</p>\n<ul>\n<li>Self-cancellation → silently ignored. Correct behavior, no action needed.</li>\n<li>External cancellation (timeout) → also silently swallowed. Component gets stuck in loading state. Usually acceptable — timeouts are rare.</li>\n</ul>\n<h3>When to add in-component error handling</h3>\n<p>Only add catch blocks when the component needs behavior <code>ErrorBoundary</code> can't provide — typically <strong>retries</strong> or <strong>timeout-specific messages</strong>. Even then, only catch what you need:</p>\n<pre><code>// Catch only external cancellation (timeouts) — everything else flows to ErrorBoundary\ncatch (OperationCanceledException ex) when (!cancellationToken.IsCancellationRequested)\n{\n    Logger.LogWarning(ex, \"Request timed out for category {CategoryId}\", CategoryId);\n    error = \"The request timed out. Please try again.\";\n}\n</code></pre>\n<p>If the component also needs to handle general errors with a retry button instead of letting <code>ErrorBoundary</code> take over:</p>\n<pre><code>catch (OperationCanceledException ex) when (!cancellationToken.IsCancellationRequested)\n{\n    Logger.LogWarning(ex, \"Request timed out for category {CategoryId}\", CategoryId);\n    error = \"The request timed out. Please try again.\";\n}\ncatch (Exception ex)\n{\n    Logger.LogError(ex, \"Failed to load products for category {CategoryId}\", CategoryId);\n    error = \"Unable to load products. Please try again.\";\n}\n</code></pre>\n<h3>Rules</h3>\n<ul>\n<li><strong>Never display <code>exception.Message</code></strong> — it may contain PII, connection strings, or internal details. Use hardcoded user-friendly messages.</li>\n<li><strong>Always log through <code>ILogger</code></strong> — the real exception goes to the logging pipeline.</li>\n<li><strong>Services must accept <code>CancellationToken</code></strong> — pass it to every async call so work stops when the component cancels.</li>\n</ul>\n<h2>Step 5 — Parameter-Driven Reloading</h2>\n<p>When data depends on a route or query parameter that changes (e.g., navigating between <code>/products/1</code> and <code>/products/2</code>), use <code>OnParametersSetAsync</code> with a guard to skip reloads for parameters that don't affect data.</p>\n<h3>Pattern: cancel-and-reload with stale data overlay</h3>\n<pre><code>@page \"/products/{CategoryId:int}\"\n@implements IAsyncDisposable\n@inject ProductService ProductService\n@inject ILogger&lt;Products&gt; Logger\n\n@if (error is not null)\n{\n    &lt;div class=\"alert alert-danger\"&gt;\n        &lt;p&gt;@error&lt;/p&gt;\n        &lt;button @onclick=\"LoadAsync\"&gt;Retry&lt;/button&gt;\n    &lt;/div&gt;\n}\nelse if (products is null)\n{\n    &lt;p&gt;Loading…&lt;/p&gt;\n}\nelse\n{\n    @if (isLoading)\n    {\n        &lt;p&gt;&lt;em&gt;Refreshing…&lt;/em&gt;&lt;/p&gt;\n    }\n    @foreach (var p in products)\n    {\n        &lt;p&gt;@p.Name — @p.Price.ToString(\"C\")&lt;/p&gt;\n    }\n}\n\n@code {\n    [Parameter] public int CategoryId { get; set; }\n    [SupplyParameterFromQuery] public string? ViewMode { get; set; } // UI-only\n\n    private CancellationTokenSource? cts;\n    private int? loadedCategoryId;\n    private List&lt;Product&gt;? products;\n    private bool isLoading;\n    private string? error;\n\n    protected override async Task OnParametersSetAsync()\n    {\n        if (CategoryId == loadedCategoryId)\n        {\n            return; // Only ViewMode changed — no reload\n        }\n\n        loadedCategoryId = CategoryId;\n        await LoadAsync();\n    }\n\n    private async Task LoadAsync()\n    {\n        if (cts is not null)\n        {\n            await cts.CancelAsync();\n            cts.Dispose();\n        }\n\n        cts = new CancellationTokenSource();\n        var cancellationToken = cts.Token; // Capture locally before await\n\n        error = null;\n        isLoading = true;\n\n        try\n        {\n            var result = await ProductService.GetByCategoryAsync(CategoryId, cancellationToken);\n            products = result;\n        }\n        catch (OperationCanceledException ex) when (!cancellationToken.IsCancellationRequested)\n        {\n            Logger.LogWarning(ex, \"Timed out loading category {CategoryId}\", CategoryId);\n            error = \"The request timed out. Please try again.\";\n        }\n        finally\n        {\n            isLoading = false;\n        }\n    }\n\n    public async ValueTask DisposeAsync()\n    {\n        if (cts is not null)\n        {\n            await cts.CancelAsync();\n            cts.Dispose();\n        }\n    }\n}\n</code></pre>\n<p>Key details:</p>\n<ul>\n<li><strong>Guard with tracked value</strong>: <code>loadedCategoryId</code> skips reloads when only UI parameters change.</li>\n<li><strong>Capture the token locally</strong> before the await — the CTS field may be replaced by a concurrent parameter change.</li>\n<li><strong>Don't null out <code>products</code></strong> on subsequent loads — keep existing data visible with an <code>isLoading</code> overlay.</li>\n<li><strong><code>IAsyncDisposable</code></strong> cancels pending work when the user navigates away.</li>\n</ul>\n<h2>Step 6 — Send Data</h2>\n<pre><code>var response = await http.PostAsJsonAsync(\"products\", newProduct);\nresponse.EnsureSuccessStatusCode();\n\nvar response = await http.PutAsJsonAsync($\"products/{id}\", updated);\nresponse.EnsureSuccessStatusCode();\n\nvar response = await http.DeleteAsync($\"products/{id}\");\nresponse.EnsureSuccessStatusCode();\n</code></pre>\n<p>Disable the submit button while saving to prevent duplicate requests. Show a saving indicator.</p>\n<h2>Step 7 — Service Abstraction for Auto or WebAssembly with Prerendering</h2>\n<p>When components run in both server and browser (Auto mode, or WebAssembly with prerendering), abstract data access behind an abstract base class:</p>\n<pre><code>public abstract class ProductServiceBase\n{\n    public abstract Task&lt;Product[]&gt; GetAllAsync(CancellationToken ct = default);\n}\n\n// Server — direct database access\npublic class ServerProductService(AppDbContext db) : ProductServiceBase\n{\n    public override async Task&lt;Product[]&gt; GetAllAsync(CancellationToken ct = default) =&gt;\n        await db.Products.ToArrayAsync(ct);\n}\n\n// Client — calls API\npublic class ClientProductService(HttpClient http) : ProductServiceBase\n{\n    public override async Task&lt;Product[]&gt; GetAllAsync(CancellationToken ct = default) =&gt;\n        await http.GetFromJsonAsync&lt;Product[]&gt;(\"api/products\", ct) ?? [];\n}\n</code></pre>\n<p>Register the appropriate implementation in each project's <code>Program.cs</code>. Components inject the abstract base class.</p>\n<h2>Don'ts</h2>\n<ul>\n<li><strong>Don't call APIs in constructors</strong> — use <code>OnInitializedAsync</code>.</li>\n<li><strong>Don't use <code>OnParametersSetAsync</code> unless data depends on a changing parameter.</strong> Use <code>OnInitializedAsync</code> for initial loads.</li>\n<li><strong>Don't inject <code>DbContext</code> in WebAssembly/Auto components</strong> — no database in the browser.</li>\n<li><strong>Don't call your own server via <code>HttpClient</code></strong> — inject the service directly.</li>\n<li><strong>Don't display <code>exception.Message</code> to users</strong> — PII risk. Log it, show a generic message.</li>\n<li><strong>Don't catch <code>OperationCanceledException</code> for self-cancellation</strong> — <code>ComponentBase</code> handles it.</li>\n</ul>\n","files":[{"path":"SKILL.md","sizeBytes":10144,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-08-24T05:42:03.715297Z","sha256":"78B64623F8FEDF530758337DA49722D756E22742E597EC35E9C87B412B45D4D9","sizeBytes":3747},"review":null,"source":{"repositoryUrl":"https://github.com/dotnet/skills","path":"plugins/dotnet-blazor/skills/fetch-and-send-data","license":"MIT","commit":"4e03bfdade5d1f9b7d1c2e95f64e31d1cb7af5ab","subtreeSha":"9FA7C3112C06D19C7816510B74A274653FDFF91640D7E24283E78DAE3F53E1E9","lastSyncedAt":"2026-11-19T19:30:03.195544Z"},"reviewedAt":"2026-08-24T05:53:23.539037Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/dotnet/skills/tree/main/plugins/dotnet-blazor/skills/fetch-and-send-data"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install dotnet-skills@llmmart"},{"target":"git","command":"git clone https://github.com/dotnet/skills.git"}]}