Langsung ke konten
Skillpedia
Website & UI (frontend)5.8k Β· #14566

fetch-and-send-data

Fungsinya

Skill ini mencakup cara memasukkan data ke komponen Blazor dan mengirimkannya kembali, termasuk status memuat dan galat. Skill ini untuk pengembang .NET yang membangun halaman Blazor yang bekerja dengan API atau database.

Kapan dipakai

  • βœ“Saat halaman Blazor perlu mengambil data dari backend atau API.
  • βœ“Saat Anda perlu mengirim data ke API dari komponen Blazor.
  • βœ“Saat Anda menginginkan status memuat dan galat yang jelas pada halaman data.

Link skill

https://github.com/dotnet/skills/blob/main/plugins/dotnet-blazor/skills/fetch-and-send-data/SKILL.md

Salin lalu tempelkan ke AI Anda (Claude, ChatGPT, atau Cursor) dan minta AI mengikuti instruksinya.

Cara pakai

Cara paling mudah: salin pesan ini dan tempelkan ke AI Anda. AI akan membaca skill dan mengikuti instruksinya.

Pesan siap tempel

Gunakan skill ini untuk membantu saya: https://github.com/dotnet/skills/blob/main/plugins/dotnet-blazor/skills/fetch-and-send-data/SKILL.md Baca file SKILL.md di link tersebut dan ikuti instruksinya untuk tugas saya.
Mau AI Anda menemukan skill seperti ini sendiri?Pasang MCP Skillpedia gratis: cukup satu baris, dan AI mencari di antara 15.000+ skill sebelum tiap tugas.Pasang dalam 1 menit β†’

Contoh permintaan ke AI

β€œMuat daftar produk dari API saya ke halaman Blazor dan tampilkan pesan memuat sampai data tiba.”

5 skill baru setiap minggu. 1 menit baca.

Cara kerjanya

Agent memeriksa mode interaktivitas aplikasi, mendaftarkan HTTP client, memuat data pada tahap lifecycle yang tepat, dan menampilkan status memuat, kosong, dan galat.

Konten teknis (SKILL.md asli)

Teks asli dari pembuat, dalam bahasa Inggris, langsung dari GitHub.

Fetch and Send Data

Step 1 β€” Read AGENTS.md

Check Interactivity Mode and Scope:

Mode Data access
None (Static SSR) Server-side: inject services/DbContext. Use [StreamRendering] for loading UX.
Server Server-side: inject services/DbContext. Guard prerender with ??= + [PersistentState].
WebAssembly Browser-side: HttpClient only. No direct server access.
Auto Both server and browser. Always go through an API.

Step 2 β€” Register HttpClient

Only needed when calling external APIs from Server, or always for WebAssembly/Auto. Server components accessing their own database should inject DbContext or a service directly.

// Named client β€” requires Microsoft.Extensions.Http NuGet
builder.Services.AddHttpClient("CatalogAPI", client =>
{
    client.BaseAddress = new Uri("https://api.example.com/");
});

// Typed client
builder.Services.AddHttpClient<CatalogClient>(client =>
    client.BaseAddress = new Uri("https://api.example.com/"));

For WebAssembly/Auto with prerendering, register in both server and .Client Program.cs.

Step 3 β€” Fetch Data

Simple load

@page "/products"
@inject CatalogClient Catalog

@if (products is null)
{
    <p>Loading…</p>
}
else
{
    @foreach (var p in products)
    {
        <p>@p.Name β€” @p.Price.ToString("C")</p>
    }
}

@code {
    private Product[]? products;

    protected override async Task OnInitializedAsync()
    {
        products = await Catalog.GetProductsAsync();
    }
}

No error handling needed in the simplest case β€” wrap the component usage in <ErrorBoundary> at the parent/layout level to catch unhandled exceptions.

Static SSR β€” StreamRendering

Without [StreamRendering], the user sees nothing until OnInitializedAsync completes:

@attribute [StreamRendering]

Only affects Static SSR. No effect on interactive components.

Prerendering guard

Prerendering calls OnInitializedAsync twice. Skip the duplicate:

[PersistentState] private Product[]? products;

protected override async Task OnInitializedAsync()
{
    products ??= await Catalog.GetProductsAsync();
}

See the support-prerendering skill for details.

Step 4 β€” Handle Errors

Use <ErrorBoundary> 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:

<ErrorBoundary>
    <ChildContent>
        <ProductList />
    </ChildContent>
    <ErrorContent>
        <div class="alert alert-danger">Something went wrong. Please refresh.</div>
    </ErrorContent>
</ErrorBoundary>

Non-cancellation exceptions (HttpRequestException, etc.) propagate to ErrorBoundary automatically β€” no catch blocks needed in the component.

Cancellation is special

ComponentBase silently swallows all OperationCanceledException β€” both self-initiated (disposal, parameter change) and external (HttpClient timeout). ErrorBoundary never sees them. This means:

  • Self-cancellation β†’ silently ignored. Correct behavior, no action needed.
  • External cancellation (timeout) β†’ also silently swallowed. Component gets stuck in loading state. Usually acceptable β€” timeouts are rare.

When to add in-component error handling

Only add catch blocks when the component needs behavior ErrorBoundary can't provide β€” typically retries or timeout-specific messages. Even then, only catch what you need:

// Catch only external cancellation (timeouts) β€” everything else flows to ErrorBoundary
catch (OperationCanceledException ex) when (!cancellationToken.IsCancellationRequested)
{
    Logger.LogWarning(ex, "Request timed out for category {CategoryId}", CategoryId);
    error = "The request timed out. Please try again.";
}

If the component also needs to handle general errors with a retry button instead of letting ErrorBoundary take over:

catch (OperationCanceledException ex) when (!cancellationToken.IsCancellationRequested)
{
    Logger.LogWarning(ex, "Request timed out for category {CategoryId}", CategoryId);
    error = "The request timed out. Please try again.";
}
catch (Exception ex)
{
    Logger.LogError(ex, "Failed to load products for category {CategoryId}", CategoryId);
    error = "Unable to load products. Please try again.";
}

Rules

  • Never display exception.Message β€” it may contain PII, connecti
Pertanyaan umum

Apakah menangani validasi formulir?

Tidak. Validasi ditangani skill formulir yang terpisah.

Apakah bekerja untuk aplikasi WebAssembly?

Ya. Skill mencakup akses data di sisi browser untuk mode WebAssembly dan otomatis.

Apakah mencakup masalah prerendering?

Tidak. Masalah prerendering ditangani skill terpisah.

Detail

Deskripsi asli dari pembuat

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).

repo: dotnet/skills

Popularitas

Bintang GitHub
5.8k
Peringkat
#14566
Lisensi
MIT
Diperbarui
2/11/2026

Apakah skill ini berguna?

0

Masuk untuk memberi suara.

Komentar

  • …

Skill lain dari repositori ini

Skill serupa