Skip to content

Core concepts

Server state & queries

A cache for data the app shows but does not own: fetched once, shared, refreshed when it goes stale, invalidated after a change, and dropped when nobody needs it.

Two kinds of state

A store holds state the app owns - what the user typed, picked or toggled. That is what undo, persistence and time travel are about. A server's answer is different: a copy of someone else's state with a shelf life. It should be fetched once and shared by every component that shows it, refreshed in the background once it is stale, refetched after a change that may have moved it, and forgotten when nobody has looked at it for a while. Undoing or persisting it would only bring back a stale copy.

BlexQueryClient (namespace Bit.Blex.Query, in the same package) is that cache - the model TanStack Query made standard, in idiomatic C#. It is not part of the state tree, DevTools or history; an effect can still read through it.

Program.cs
builder.Services.AddBitBlexServices();
builder.Services.AddBitBlexQueries(options =>
{
    options.StaleTime = TimeSpan.FromSeconds(30);   // defaults for every query
});

Querying

A query is a key - an ordered list of parts, general to specific - and a fetch. In a component that inherits BlexComponentBase, UseQuery observes it for the component's lifetime and re-renders as it changes. Call it from OnParametersSet, before any await: a call site keeps an observer per key it asks for, and once a parameter pass is over it releases the keys it stopped asking for - so a key that follows a parameter is swapped, and one call in a loop over items keeps one observer per item.

@inherits BlexComponentBase
@inject TodoApi Api

@if (_todo.IsLoading) { <Spinner /> }
else if (_todo.Data is { } todo) { <h2>@todo.Title</h2> }
else if (_todo.Error is { } error) { <p>@error.Message</p> }

@code {
    [Parameter] public int Id { get; set; }
    private BlexQuery<Todo> _todo = default!;

    protected override void OnParametersSet()
        => _todo = UseQuery(["todos", Id], ct => Api.GetTodoAsync(Id, ct));
}

Or straight from markup, with no base class:

<BlexQueryView TData="Todo" Key="@([]"todos", Id])" Fetch="ct => Api.GetTodoAsync(Id, ct)">
    <LoadingContent><Spinner /></LoadingContent>
    <ErrorContent Context="error">@error.Message</ErrorContent>
    <ChildContent Context="todo"><h2>@todo.Title</h2></ChildContent>
</BlexQueryView>

What an observer reports

Member Description
Data / HasData The cached data (or the previous key's, with KeepPreviousData).
Status Pending (no data yet), Error (the last fetch failed), Success.
FetchStatus Idle or Fetching - independent of Status: a background refetch is Success and Fetching at once.
IsLoading / IsRefetching Fetching with no data to show, versus fetching while showing data.
IsStale / DataUpdatedAt Whether the data is older than the stale time (or invalidated), and when it was fetched.
Error / FailureCount / FailureReason The last fetch's error; how many attempts failed; the latest failure while it is still being retried.
RefetchAsync() / WhenSettledAsync() Fetch again now; wait until no fetch is running. Neither throws.
Live: One request, two readers

This page was prerendered: the server fetched the products and handed them over, so the browser started with them and sent no request. Both panels read the key ["products"]; mounting together costs one request. The data stays fresh for 15 seconds, then a refetch shows the cached copy while it runs. Make a change on the "server" and see the cache catch up only when it refetches.

Requests sent–
StatusSuccess
FetchStatusIdle
IsStalefalse
Left
  • Keyboard 12 in stock
  • Mouse 30 in stock
  • Monitor 4 in stock
Right
  • Keyboard 12 in stock
  • Mouse 30 in stock
  • Monitor 4 in stock
Live: A third reader, in markup

The same key from markup, with no UseQuery and no base class: <BlexQueryView> observes ["products"] for as long as it is on the page, so it joins the cache entry the panels above already fill - Requests sent does not move - and renders whichever of its three templates fits.

3 products, 46 units in stock: Keyboard, Mouse, Monitor.

<BlexQueryView TData>

Parameter Description
BlexQueryKey Key Required. Which query; a new key moves the view to that query, keeping the previous data meanwhile with KeepPreviousData.
Func<CancellationToken, Task<TData>> Fetch Required. Fetches the data; the closure from the latest render is the one used.
BlexQueryOptions? Options How to fetch it - stale time, retries, polling, Enabled.
RenderFragment<TData>? ChildContent Rendered with the data once there is some. Data wins over an error: a failed refetch keeps showing what was fetched before.
RenderFragment? LoadingContent Rendered while there is neither data nor an error.
RenderFragment<Exception>? ErrorContent Rendered with the error when the query failed and has no data to show instead.
BlexQuery<TData>? Query Not a parameter: the observer, through a @ref, for a "refreshing" hint from IsRefetching.

Freshness, retries and garbage collection

BlexQueryOptions (unset values come from AddBitBlexQueries)

Member Description
StaleTime How long fetched data counts as fresh. Fresh data is served without a request; stale data is served too, and refetched in the background on mount and focus. Default 0; TimeSpan.MaxValue keeps it fresh until invalidated.
GcTime How long a query nobody observes stays cached. Default 5 minutes.
RetryCount / RetryDelay Failed fetches are retried with exponential backoff (doubling, up to 30 s). Default 3 retries, 1 s.
Enabled Off: the observer reads what is cached but never fetches - a dependent query waiting for its input.
RefetchInterval Polls while observed.
RefetchOnMount / RefetchOnFocus Whether a new observer, or the tab becoming visible / the network returning, refetches stale data. Default on.
KeepPreviousData When the key changes (the next page), keep showing the previous key's data, flagged IsPlaceholderData, until the new one arrives.
NetworkMode Online (the default): while offline the fetch waits, Paused, and goes on once the network returns. Always: fetches whatever the network - for data that does not come from it.
Dependent, polling and long-lived queries
// Dependent: waits until there is a user to load the orders of. Enabled flips on with the id,
// and the same call site starts fetching.
_orders = UseQuery(["orders", UserId], ct => Api.GetOrdersAsync(UserId!.Value, ct),
    new BlexQueryOptions { Enabled = UserId is not null });

// Polling: refetched every 10 s while something observes it - and never while nothing does.
_status = UseQuery(["build-status", BuildId], ct => Api.GetStatusAsync(BuildId, ct),
    new BlexQueryOptions { RefetchInterval = TimeSpan.FromSeconds(10) });

// Reference data: fresh until invalidated, kept an hour after the last observer left,
// and not refetched just because the tab came back.
_countries = UseQuery(["countries"], Api.GetCountriesAsync, new BlexQueryOptions
{
    StaleTime = TimeSpan.MaxValue,
    GcTime = TimeSpan.FromHours(1),
    RefetchOnFocus = false,
});

BlexQueryClientOptions (AddBitBlexQueries)

Option Description
TimeSpan StaleTime The default stale time of every query. Default 0: always stale, refetched on every mount and focus.
TimeSpan GcTime How long an unobserved query stays cached. Default 5 minutes.
int RetryCount / TimeSpan RetryDelay Retries for a failed fetch, with exponential backoff from the delay up to 30 s. Default 3 and 1 s. A mutation does not inherit them: it retries only when its own options say so.
BlexNetworkMode NetworkMode Online (the default) pauses fetches and mutations while offline; Always never does.
bool SyncAcrossTabs Passes invalidations by key on to the app's other tabs over a BroadcastChannel. Default off.

One fetch runs per key at a time: observers that mount while it runs join it. An explicit refetch or an invalidation cancels a running fetch and starts over, and only the latest fetch's outcome is committed - so a slow response can never overwrite a newer one. A failed refetch keeps the data it had alongside the error; FailureReason is set while a failure is still being retried.

Mutations and optimistic updates

A mutation sends a change. OnMutate can apply it to the cache at once with Optimistic, which returns the rollback a failure applies automatically; Invalidates names the keys to refetch once the change settles. The mutation stays pending until those refetches land, so "saved" never shows next to the list from before the save. MutateAsync never throws: a failure lands in Error.

_add = Watch(QueryClient.Mutation<string, Product>(
    (name, ct) => Api.AddProductAsync(name, ct),
    new()
    {
        // Shown at once; rolled back automatically if the server says no.
        OnMutate = name => QueryClient.Optimistic<IReadOnlyList<Product>>(
            ["products"], products => [.. products ?? [], new Product(-1, name, 0)]),

        // Whatever happened, the server's list has moved: refetch it.
        Invalidates = ["products"],
    }));

private async Task Add() => await _add.MutateAsync(_name);
Live: Optimistic add, with rollback

The new product appears at once. Tick "server rejects writes" and it disappears again when the server says no.

Mutation statusIdle
Errornull
Overlapping optimistic updates

Rolling back restores the previous data only while the cache still holds that update's value. If something newer landed meanwhile - a second mutation's optimistic value, a refetch - the key is invalidated instead. Restoring an old snapshot over newer data is how overlapping optimistic updates corrupt each other.

Rolling back more than the cache

OnMutate returns an IBlexRollback - whatever must be undone if the change fails. Optimistic returns one for a cached key; BlexRollback.From(action) makes one from any code (a store's counter, a toast), and BlexRollback.Combine(...) joins several into one - undone together, the last applied first, and at most once. The callbacks follow the outcome: OnSuccess with the server's answer, OnError with the failure, OnSettled either way.

_add = Watch(QueryClient.Mutation<Todo, Todo>(
    (todo, ct) => Api.AddAsync(todo, ct),
    new()
    {
        OnMutate = todo =>
        {
            var list = QueryClient.Optimistic<IReadOnlyList<Todo>>(["todos"], todos => [.. todos ?? [], todo]);
            Badge.Increment();                                      // a store, outside the cache

            // Undone together on failure, the badge first.
            return BlexRollback.Combine(list, BlexRollback.From(Badge.Decrement));
        },
        OnSuccess = (saved, _) => QueryClient.SetQueryData(["todos", saved.Id], saved),
        OnError = (error, todo) => Toasts.Show($"\"{todo.Title}\" was not saved: {error.Message}"),
        OnSettled = _ => _input = "",
        Invalidates = ["todos"],
        RetryCount = 2,
    }));

BlexMutationOptions<TArg, TResult>

Option Description
Func<TArg, IBlexRollback?>? OnMutate Runs before the change is sent - the place for an optimistic update. Return what a failure must undo.
Action<TResult, TArg>? OnSuccess Runs with the server's answer - the place to SetQueryData the entity it returned.
Action<Exception, TArg>? OnError Runs after a failure, once the optimistic update has been rolled back.
Action<TArg>? OnSettled Runs last, whichever way it went.
IReadOnlyList<BlexQueryKey>? Invalidates Keys to invalidate once the change settles, success or failure. The mutation stays pending until the observed ones have refetched - unless the app is offline, where it settles without waiting for them.
int RetryCount / TimeSpan RetryDelay Retries for a failed call. Default 0: a change is not repeated unless asked to.
BlexNetworkMode? NetworkMode Whether a call waits for the network while offline (paused, its optimistic update shown). null uses the client's.

BlexMutation<TArg, TResult>

Member Description
Task MutateAsync(TArg, CancellationToken) Sends the change: OnMutate, the call (with retries), the success or error callback - rolling back on failure - the invalidations, then OnSettled. Never throws. A cancelled call rolls back and returns to Idle, not Error.
BlexMutationStatus Status Idle, Pending, Success or Error - of the latest call, when calls overlap.
bool IsIdle / IsPending / IsSuccess / IsError Status, one flag at a time.
bool IsPaused Pending, and waiting for the network to return.
TResult? Data / Exception? Error / TArg? Arg The latest call's answer, failure and argument.
void Reset() Back to Idle, forgetting the latest outcome; a call still running no longer reports to it.
event Action? Changed / PropertyChanged Raised on every change - Watch(...) re-renders a component on it, and XAML binds to it.

Invalidation and direct cache access

InvalidateAsync(["todos"]) marks every query whose key starts with those parts as stale and refetches the ones being watched; the rest refetch when next observed. Pass exact: true for one key, or a predicate. SetQueryData writes a response you already have (the entity a save returned), GetQueryData reads one, and Cancel/Remove stop or drop queries.

await queries.InvalidateAsync(["todos"]);                 // every todos query
await queries.InvalidateAsync(["todos", 42], exact: true); // just this one

var saved = await api.SaveAsync(todo, ct);
queries.SetQueryData(["todos", saved.Id], saved);           // no refetch needed for this one

var cached = queries.GetQueryData<Todo>(["todos", 42]);
Live: The cache, inspected

GetQueries() lists every cached query, and CacheChanged says when to look again - what a devtools panel for the cache is built from. Write into the cache directly, cancel a fetch, drop one query or all of them, and watch the entries and the panels above follow.

Cached queries3
FetchingCount0
GetQueryData(["products"])3 products, 46 in stock
KeyStatusFetchObserversUpdated (UTC)
["activity"] Success Idle 1 12:07:11
["activity-page",1] Success Idle 1 12:07:11
["products"] Success Idle 3 12:07:11

Zeroing the stock sends nothing: the panels change because the cache did. The next refetch brings the server's numbers back. A removed query that still has an observer starts over on a fresh entry - what Clear() on sign-out relies on, so the next user never sees the last one's data. An entry with no observers is dropped once its GcTime passes (5 minutes by default).

BlexQueryClient

Member Description
BlexQuery<T> Query<T>(key, fetch, options?) Observes a query by hand - what UseQuery does for a component. Dispose the observer when done.
BlexInfiniteQuery<TPage, TParam> InfiniteQuery(key, fetchPage, initialPageParam, getNextPageParam, options?) The same for a paged query - what UseInfiniteQuery wraps.
Task<T> FetchAsync<T>(key, fetch, options?, cancellationToken) The read-through for effects and services: fresh cached data, or a fetch - joining one already running. Throws when the fetch fails or is cancelled.
Task PrefetchAsync<T>(key, fetch, options?) Warms the cache for a query nobody shows yet. Never throws.
T? GetQueryData<T>(key) / bool TryGetQueryData<T>(key, out T?) Reads what is cached, without fetching.
void SetQueryData<T>(key, T) / SetQueryData<T>(key, Func<T?, T>) Writes data you already have - the entity a save returned - as fresh, notifying every observer.
BlexOptimisticUpdate<T> Optimistic<T>(key, Func<T?, T>) Writes an optimistic value and returns its rollback - for OnMutate.
BlexMutation<TArg, TResult> Mutation(mutate, options?) Creates a mutation.
Task InvalidateAsync(key, exact = false) / InvalidateAsync(Func<BlexQueryKey, bool>) Marks the covered queries stale and refetches the observed ones; completes once those refetches settle.
Task RefetchAsync(key, exact = false) Refetches the observed queries the key covers now, without marking the rest stale.
void Cancel(key, exact = false) Cancels their running fetches; they keep the data they had.
void Remove(key, exact = false) / void Clear() Drops queries from the cache; an observer still watching one starts over on a fresh entry - the sign-out move.
bool IsOnline / NotifyOffline() / NotifyReconnected() The network as the cache was told. <BlexProvider> calls them from the browser's events where requests leave from the device.
void NotifyFocused() Refetches the stale observed queries whose observers ask for RefetchOnFocus. <BlexProvider> calls it when the tab becomes visible.
IReadOnlyList<BlexQueryInfo> GetQueries() / int FetchingCount / event CacheChanged Inspection: every cached query, how many are fetching, and when anything changed.
JsonObject Dehydrate() / void Hydrate(JsonObject) The fetched queries as JSON, and back - what the prerender handoff uses.
BlexQueryClientOptions Options The defaults every query starts from.

With options.SyncAcrossTabs = true (in AddBitBlexQueries), an invalidation by key reaches the app's other tabs too - over a BroadcastChannel, through <BlexProvider>, on Blazor Server as well - so a change saved in one tab refetches the list every other tab shows. Keys travel as their text and match part by part, prefixes included; an invalidation by predicate stays in its tab. This site turns it on: open this page in a second tab, press Invalidate ["products"] above in this one, and Requests sent climbs over there.

Paged and infinite queries

For numbered pages, put the page in the key and turn on KeepPreviousData. Each page is a query of its own - cached, shared and refetched like any other - and while the next one loads, the observer keeps showing the page it had, flagged IsPlaceholderData, instead of flashing back to a spinner. PrefetchAsync fetches the page after it before anyone asks, so the click lands on cached data.

// ActivityPager.razor - the page is a parameter, so each new number is a new key at this call site.
[Parameter] public int Page { get; set; } = 1;

protected override void OnParametersSet()
    => _page = UseQuery(["activity-page", Page], ct => Api.GetActivityPageAsync(Page, ct),
           new BlexQueryOptions { KeepPreviousData = true, StaleTime = TimeSpan.FromSeconds(15) });

// While the next page loads: _page.Data is the previous page, and _page.IsPlaceholderData is true.

// Before the user asks for it:
await QueryClient.PrefetchAsync(["activity-page", Page + 1], ct => Api.GetActivityPageAsync(Page + 1, ct));
Live: Page by page, without the flash

Next page asks for a key nobody has fetched: the list stays, dimmed, flagged IsPlaceholderData, until the new page lands. Go back and the earlier page is served from the cache at once. Prefetch the next page first and stepping onto it is instant too.

Page 1 of 4
Key ["activity-page",1]
IsPlaceholderData false
FetchStatus Idle
  • #1: Keyboard shipped
  • #2: Mouse counted
  • #3: Monitor received

Infinite queries

A feed, "load more", infinite scroll: UseInfiniteQuery (or QueryClient.InfiniteQuery) keeps the pages loaded so far as one cached query. getNextPageParam reads the next page's param - a page number, a cursor - off the last page, or returns null when there is none, so use a nullable type for a number. FetchNextPageAsync appends the next page; asked again while it loads, it joins that request, and with a fetch already running it waits for it and follows the pages it brings.

Everything a query does applies to the pages as a whole - freshness, retries, invalidation, refetch on focus, the prerender handoff. A refetch loads every page again, in order, each param following from the page before as the server returns it now: an item inserted since moves every cursor after it. A failed next page keeps the pages loaded before it, and can simply be asked for again.

@inherits BlexComponentBase

@foreach (var entry in _activity.Pages.SelectMany(p => p.Entries))
{
    <li>@entry</li>
}
@* IsPending: before the first page arrives there is no next page either, but nothing is "all loaded". *@
<button @onclick="() => _activity.FetchNextPageAsync()"
        disabled="@(_activity.IsPending || !_activity.HasNextPage || _activity.IsFetchingNextPage)">Load more</button>

@code {
    private BlexInfiniteQuery<ActivityPage, int?> _activity = default!;

    protected override void OnParametersSet()
        => _activity = UseInfiniteQuery<ActivityPage, int?>(
            ["activity"],
            (page, ct) => Api.GetActivityPageAsync(page, ct),
            initialPageParam: 1,
            getNextPageParam: (last, _) => last.Next);   // null on the last page
}
Live: Load more

Each page is one request; "Invalidate" refetches every page loaded so far, in order.

Pages loaded1
HasNextPagetrue
FetchStatusIdle
  • #1: Keyboard shipped
  • #2: Mouse counted
  • #3: Monitor received

Prerendering

With <BlexProvider>, the queries a prerender fetched are handed to the interactive render through PersistentComponentState, so it shows them at once instead of fetching them again. Two things make that work: the prerender has to wait for the fetch, or the HTML carries a spinner and nothing is handed over; and the query needs a stale time, or the handed-over data is stale on arrival and refetched in the background anyway.

protected override async Task OnParametersSetAsync()
{
    _todo = UseQuery(["todos", Id], ct => Api.GetTodoAsync(Id, ct),
                     new BlexQueryOptions { StaleTime = TimeSpan.FromMinutes(1) });

    await _todo.WhenSettledAsync();   // the prerendered HTML carries the data, and so does the handoff
}

Underneath, the provider calls QueryClient.Dehydrate() at the end of the prerender - the successfully fetched queries as JSON - and Hydrate(...) before the interactive render asks for them. Outside Blazor, the same pair moves a cache from one host to another.

From effects, services and tests

FetchAsync is the read-through for code that is not a component: it returns fresh cached data, joins a fetch already running, and throws when the fetch fails. PrefetchAsync warms the cache (on hover, before navigating) and never throws. <BlexProvider> refetches the stale queries being watched when the tab becomes visible again or the browser comes back online; outside a browser, call NotifyFocused() and NotifyReconnected() where your app learns of it.

[BlexStore(Name = "checkout")]
public partial class CheckoutStore(BlexQueryClient queries, ShopApi api)
{
    [BlexState] private decimal _shipping;

    [BlexEffect]
    private async Task OnQuote(string country, CancellationToken ct)
    {
        // Shares the cache - and any request already running - with the components showing rates.
        var rates = await queries.FetchAsync(["rates", country], c => api.GetRatesAsync(country, c), cancellationToken: ct);
        Shipping = rates.Standard;
    }
}

Every wait - staleness, retries, polling, garbage collection - runs on the manager's TimeProvider, and timers run on its Dispatcher. A test hands the client a manager with a fake clock and advances it.

Offline

A request that cannot reach the server should not fail - it should wait. While QueryClient.IsOnline is false, fetches and mutations pause (FetchStatus.Paused, IsPaused) instead of spending their retries, and go on from where they were once the network returns; a paused mutation's optimistic update is on screen meanwhile. <BlexProvider> follows the browser's offline and online events where requests leave from the device - WebAssembly and Hybrid. On Blazor Server they leave from the server, so the browser's network does not pause them. A native MAUI app calls NotifyOffline() and NotifyReconnected() from Connectivity.ConnectivityChanged.

@if (_todos.IsPaused)
{
    <p>Offline - the list will load once you are back.</p>
}
@if (_save.IsPaused)
{
    <p>Saved here; it is sent as soon as the network returns.</p>
}

// Data that does not come from the network runs offline too:
UseQuery(["drafts"], ct => Drafts.LoadFromIndexedDbAsync(ct), new BlexQueryOptions { NetworkMode = BlexNetworkMode.Always });

// Native MAUI: tell the cache yourself.
Connectivity.ConnectivityChanged += (_, e) =>
{
    if (e.NetworkAccess == NetworkAccess.Internet) queries.NotifyReconnected();
    else queries.NotifyOffline();
};
Live: Offline, on demand

NotifyOffline() is what the browser's offline event does for you. Go offline, then refetch the products: the fetch pauses instead of failing. Add a product: the mutation pauses too, its optimistic row already on screen. Back online, both carry on from where they were. Leaving the page puts the network back.

IsOnlinetrue
products FetchStatusIdle
mutationIdle
Products shown3
An unhandled error has occurred. Reload 🗙