Saltar al contenido
Skillpedia
Sitios e interfaces (frontend)5,8 mil · #14566

fetch-and-send-data

Qué hace

Esta skill cubre cómo llevar datos a componentes Blazor y enviarlos de vuelta, incluidos los estados de carga y de error. Está pensada para desarrolladores de .NET que construyen páginas Blazor que trabajan con una API o una base de datos.

Cuándo usarla

  • ✓Cuando una página Blazor necesita obtener datos de un backend o de una API.
  • ✓Cuando necesitas enviar datos a una API desde un componente Blazor.
  • ✓Cuando quieres estados de carga y error claros en una página de datos.

Link de la skill

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

Cópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.

Cómo usar

La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.

Mensaje listo para pegar

Usa esta skill para ayudarme: https://github.com/dotnet/skills/blob/main/plugins/dotnet-blazor/skills/fetch-and-send-data/SKILL.md Lee el archivo SKILL.md de ese link y sigue sus instrucciones en mi tarea.
¿Quieres que tu IA encuentre skills como esta por sí sola?Instala el MCP gratis de Skillpedia: una línea, y busca entre 15.000+ skills antes de cada tarea.Instalar en 1 minuto →

Ejemplo de qué pedirle a la IA

“Carga la lista de productos de mi API en una página Blazor y muestra un mensaje de carga hasta que llegue.”

5 skills nuevas por semana. 1 minuto de lectura.

Cómo funciona

El agente comprueba el modo de interactividad de la app, registra el cliente HTTP, carga los datos en el paso adecuado del ciclo de vida y muestra los estados de carga, vacío y error.

Contenido técnico (SKILL.md original)

Texto original del autor, en inglés, directo de 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
Preguntas frecuentes

¿Gestiona la validación de formularios?

No. La validación la cubre una skill de formularios aparte.

¿Funciona con apps WebAssembly?

Sí. Cubre el acceso a datos en el navegador para los modos WebAssembly y automático.

¿Cubre problemas de prerenderizado?

No. Los problemas de prerenderizado los maneja una skill aparte.

Detalles

Descripción original del autor

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

Popularidad

Estrellas en GitHub
5,8 mil
Posición en el ranking
#14566
Licencia
MIT
Actualizada
2/11/2026

¿Te sirve esta skill?

0

Entra para votar.

Comentarios

  • …

Más skills de este repositorio

Skills parecidas