Skip to content

Blazor Integration

Swr.Net works with both Blazor Server and Blazor WebAssembly. AddSwrForBlazor() registers ISwr as Scoped, meaning each Blazor circuit gets its own independent cache — user data never leaks between sessions.

Program.cs
builder.Services.AddSwrForBlazor();

Optionally configure global defaults:

Program.cs
builder.Services.AddSwrForBlazor(options =>
{
options.StaleTime = TimeSpan.FromSeconds(30);
options.CacheTime = TimeSpan.FromMinutes(5);
});

Use Use<T> in OnInitialized with a fetcher and onChange callback to load data without blocking the page render:

Components/Pages/Weather.razor
@using System.Net.Http.Json
@using Swr.Net
@inject ISwr Swr
@inject HttpClient Http
@if (result?.Data is not null)
{
<h2>@result.Data.Summary</h2>
<p>Temperature: @result.Data.TemperatureC °C</p>
}
else if (result is null or { IsLoading: true })
{
<p>Loading...</p>
}
else if (result?.Error is not null)
{
<p class="error">@result.Error</p>
}
@code {
private SwrResult<WeatherForecast>? result;
protected override void OnInitialized()
{
result = Swr.Use<WeatherForecast>("/api/weather",
async key => await Http.GetFromJsonAsync<WeatherForecast>(key),
onChange: () => InvokeAsync(StateHasChanged));
}
}
  • Use<T> returns immediately — if cached data exists, it’s available right away; otherwise IsLoading is true
  • The onChange callback fires when the fetch or background revalidation completes, triggering a re-render with fresh data
  • The first argument is the cache key, the second is the fetcher function that knows how to retrieve the data
  • Data is checked before the loading state so that cached data renders instantly, even while revalidating

A SwrResult<T> can be in three states:

  1. IsLoading == true — a network request is in progress
  2. Error is not null — the fetch failed; check Error for the message
  3. Data is not null — data is available (may be fresh or from cache)
@if (result?.Data is not null)
{
<h2>@result.Data.Name</h2>
@if (result.IsFromCache)
{
<span class="badge">Refreshing...</span>
}
}

Override global options for a specific fetch:

var options = new SwrOptions
{
StaleTime = TimeSpan.FromSeconds(10),
CacheTime = TimeSpan.FromMinutes(1),
RetryCount = 5
};
result = Swr.Use<Dashboard>("/api/dashboard",
async key => await Http.GetFromJsonAsync<Dashboard>(key),
options: options,
onChange: () => InvokeAsync(StateHasChanged));

Per-request options take precedence over the global options configured in Program.cs.

Use MutateAsync to execute a mutation and invalidate related cache entries:

// Execute a mutation and invalidate related cache entries
await Swr.MutateAsync(
async () => await Http.PutAsJsonAsync($"/api/users/{userId}", updates),
"/api/users/me", "/api/users"
);

If the mutation throws, no cache keys are evicted — the cache stays consistent.

Force a cache refresh without executing a mutation:

Swr.Invalidate("/api/users/me"); // Remove one exact key
Swr.InvalidateByPrefix("/api/users"); // Remove all keys starting with prefix
Swr.InvalidateAll(); // Clear the entire cache