Core concepts
Actions
An action is a named, batched, recorded unit of change. Everything that mutates state becomes one - even a direct property assignment.
The convention
Mark a method named OnXxx with [BlexAction]. The generator emits a
public Xxx(...) wrapper that runs your method inside a dispatch: all the
mutations it makes are folded into one notification and one time-travel entry.
[BlexAction]
private void OnIncrement() => Count += Step;
[BlexAction]
private void OnReset()
{
Count = 0; // both assignments are folded into
Step = 1; // a single "Reset" action and one render
}
public void Increment()
=> Dispatch("Increment", () => OnIncrement());
public void Reset()
=> Dispatch("Reset", () => OnReset());Naming
The wrapper name comes from the method name with the On prefix stripped, or from
[BlexAction(Name = "…")]. The Name is used in two different ways
depending on whether it is a valid C# identifier:
| Declaration | Method you call | Label in DevTools / history |
|---|---|---|
[BlexAction] void OnIncrement() | Increment() | Increment |
[BlexAction(Name = "Bump")] void OnIncrement() | Bump() | Bump |
[BlexAction(Name = "Apply preset")] void OnApplyPreset() | ApplyPreset() | Apply preset |
In other words: a name containing spaces (or anything else illegal in an identifier, or a C#
keyword) is treated purely as a display label, and the method name still comes from the
On prefix. A method that neither starts with On nor supplies a
usable name is BLEX002.
Arguments become the payload
Action parameters are captured as name/value pairs and travel with the action to middleware, subscribers, the test harness and the DevTools monitor. Nothing to declare.
[BlexAction]
private void OnSetStep(int step) => Step = step;
[BlexAction]
private void OnAddItem(string name, int quantity = 1) => /* ... */;
// store.SetStep(5) is recorded as:
// ActionName "SetStep"
// Args [ { Name = "step", Value = 5 } ]
// DevTools { "step": 5 }
Capture is skipped entirely when nothing is observing - the generated wrapper checks
IsObserved first, so an app with no middleware, no DevTools and no subscribers
pays nothing for the payload.
Parameter rules:
- Default values and
paramsare preserved on the wrapper. ref,outandinparameters are rejected - the wrapper has to capture them by value (BLEX013).- Generic action methods are rejected; the wrapper cannot carry type parameters (
BLEX014).
Typed actions
A method call is only half of what an action is. Middleware, subscribers, history filters and
tests also need to recognize an action after the fact and read its payload - and a
string like "Apply preset" plus an object looked up by parameter name
breaks silently the day someone renames either. So the generator also emits a descriptor for
every action and effect, in a nested Actions class on the store.
[BlexStore(Name = "counter")]
public partial class CounterStore
{
[BlexState] private int _count;
[BlexState] private int _step = 1;
[BlexAction] private void OnIncrement() => Count += Step;
[BlexAction] private void OnSetStep(int step) => Step = step;
[BlexAction(Name = "Apply preset")]
private void OnApplyPreset(int count, int step) { Count = count; Step = step; }
}
public static class Actions
{
public static readonly BlexAction<CounterStore> Increment = ...;
public static readonly BlexAction<CounterStore, int> SetStep = ...;
public static readonly BlexAction<CounterStore, (int Count, int Step)> ApplyPreset = ...; // Name: "Apply preset"
}
The payload type follows the parameters:
| Declaration | Descriptor |
|---|---|
void OnIncrement() | BlexAction<CounterStore> |
void OnSetStep(int step) | BlexAction<CounterStore, int> - the argument itself |
void OnApplyPreset(int count, int step) | BlexAction<CounterStore, (int Count, int Step)> - a tuple named after the parameters |
Task OnSearch(string query, CancellationToken ct) | BlexAction<SearchStore, string> - an effect's token is supplied by the wrapper, so it is not part of the payload |
void OnTag(params string[] tags) | BlexAction<S, string[]> |
When a parameter cannot name a tuple element - rest, toString, an
item2 in first position, two parameters that differ only in case - the tuple is
simply left unnamed ((string, int), read as Item1,
Item2).
// Recognize an action in any context, by symbol - a rename breaks the build, not the feature.
if (CounterStore.Actions.ApplyPreset.TryGetPayload(ctx, out var preset))
Console.WriteLine($"count {preset.Count}, step {preset.Step}");
bool isStep = CounterStore.Actions.SetStep.Matches(ctx);
// Dispatch as data, through the generated wrapper:
await CounterStore.Actions.ApplyPreset.InvokeAsync(counter, (10, 2));
await CounterStore.Actions.Increment.InvokeAsync(counter);
BlexAction<TStore, TPayload>
| Member | Description |
|---|---|
string Name |
The action name as dispatched - the display label when it has one ("Apply preset"). |
Type StoreType |
The store type the action belongs to. |
IReadOnlyList<string> ParameterNames |
The parameter names, in declaration order. |
bool Matches(BlexActionContext / BlexPreActionContext / BlexActionErrorContext) |
Whether the dispatched, about-to-run or failed action is this one: same store type, same name. Every instance of the store matches, scoped ones included. |
bool TryGetPayload(context, out TPayload) |
Reads the payload as the type the action takes, when the context is this action and its arguments were captured. |
TPayload GetPayload(context) |
The same, throwing when it is another action. |
TPayload ReadPayload(IReadOnlyList<BlexActionArg>) |
Rebuilds the payload from any argument list - a recorded one, or one assembled by hand. |
Task InvokeAsync(TStore, TPayload) |
Dispatches the action through its generated wrapper. Completed already for a synchronous action. BlexAction<TStore> has InvokeAsync(TStore). |
Task InvokeAsync(IBlexStore, IReadOnlyList<BlexActionArg>?) |
The untyped form on BlexActionDescriptor: arguments matched by name, JSON values converted with BlexJson.Options. |
The descriptor also plugs straight into the pipeline APIs:
manager.SubscribeToAction(CounterStore.Actions.ApplyPreset, ...),
options.UseFilter(CounterStore.Actions.SetStep, ...), and the test
harness's Log.PayloadsOf(...).
A store that already declares something called Actions - a property, a nested
type, or state whose generated property is Actions - keeps compiling exactly
as before, but without the typed descriptors, and the generator says so with warning
BLEX020. Its actions stay dispatchable by name. Rename the member to get them.
Dispatching by name
Because every action is described as data, it can also be sent as data:
manager.DispatchAsync("store/Action", payload) finds the action by its qualified
name - the label DevTools shows - converts a JSON payload keyed by parameter name, and calls the
generated wrapper. The action passes the filters, reaches middleware and is recorded exactly as
a direct call would be. Direct assignments ("counter/Set Count") and
"counter/ResetState" are dispatchable too, and an optional parameter the payload
leaves out takes its declared default.
@inject BlexManager Manager
await Manager.DispatchAsync("counter/Apply preset", new JsonObject { ["count"] = 7, ["step"] = 2 });
await Manager.DispatchAsync("counter/Set Count", new JsonObject { ["Count"] = 42 });
await Manager.DispatchAsync("counter/ResetState");
// Arguments match by name (case-insensitively as a fallback) and convert the way stored
// state does: "High" for an enum, 12.5 for a decimal, an array for params.
// An unknown action throws InvalidOperationException; a missing argument, ArgumentException.
// Already-materialized arguments, e.g. the ones recorded when the action first ran:
await Manager.DispatchAsync(ctx.QualifiedName, ctx.Args);
It is what the DevTools dispatcher and the testing package's
action replay are built on: a log recorded in one session dispatches
again in another, which is the practical meaning of "a predictable state model". That makes the
name an action's identity, so two actions dispatched under one name - two display labels alike,
or a label such as "Set Count" that a direct assignment already records - fail the
build with BLEX021.
Pick a preset or write your own: the qualified name and the JSON payload are all DispatchAsync needs. The typed subscription below reads Apply preset's payload as (int Count, int Step).
Dispatchable on counter:
Increment, Decrement, SetStep, Apply preset, Set Count, Set Step, ResetState
Batching
This is the point of actions. Assigning three fields directly produces three actions and three renders; doing it inside one action produces one of each.
Watch the notification counter - and the Inspector's action feed - after each button.
The first button dispatches Set Count and Set Step separately.
The other two dispatch exactly one action and render once. Each click moves both fields on from
where they are: assigning a field the value it already holds is no change, and notifies nobody.
Direct assignment: the "Set X" action
Generated properties have public setters (unless the store
enforces actions), and assigning one from outside any
action is still a first-class action named Set X, carrying the assigned value as
its payload. It is vetoable by middleware, recorded for undo/redo and visible in DevTools - so
nothing can change state behind the pipeline's back.
store.Count = 5;
// Recorded as:
// ActionName "Set Count"
// Args [ { Name = "Count", Value = 5 } ]Enforcing actions
A Set X is still an anonymous change: it says what moved, never
why, and any component holding the store can make one. A Flux store is supposed to
guarantee the opposite - every change is a deliberate, named action. Opt in with
EnforceActions and the guarantee is checked by the compiler:
[BlexStore(Name = "account", EnforceActions = true)]
public partial class AccountStore
{
[BlexState] private decimal _balance;
[BlexAction] private void OnDeposit(decimal amount) => Balance += amount;
public void Sneak() => Balance = 0; // compiles, but throws at runtime: not inside an action
}
account.Deposit(10); // fine
account.Balance = 0; // CS0272: the setter is private
- The generated state setters are
private, so assigning one from outside the store does not compile (CS0272). - An assignment the store's own code makes outside any action throws
InvalidOperationExceptiononce the store is registered. Assignments in the constructor, before anyone can observe the store, are fine. - Restores, hydration and
ResetStateare not assignments and work as usual; so do effects, whose bodies run inside their action. - No
Set Xdescriptors are offered for dispatch by name - such an action can never have been recorded.
Two-way binding needs a setter, so bind such a store's state through an action instead:
@* @bind needs a setter; route it through an action instead *@
<input @bind:get="Search.Query" @bind:set="Search.SetQuery" />
This site's AccountStore is [BlexStore(EnforceActions = true)]. Deposit and Withdraw are actions and work. SneakBonus() is the store's own code assigning Balance outside any action - it compiles, and throws. The compile-time half cannot run in a browser: account.Balance = 0 from this page would not build.
Dispatchable on account: Deposit, Withdraw, ResetState
- and no Set Balance, since nothing can ever have recorded one.
Batch: ad-hoc grouping
When the grouping is a caller's concern rather than the store's, Batch wraps any
set of mutations into one named action - Pinia's $patch or MobX's
runInAction.
// One notification, one history entry, one middleware pass. Give it a name no action
// of the store has: anything matching that action by name would take the batch for it.
store.Batch("Apply defaults", () =>
{
store.Count = 10;
store.Step = 5;
});ResetState
Every store snapshots itself the first time it is registered with the manager.
ResetState() restores that snapshot as a normal ResetState action:
vetoable, observable, persisted and undoable. It is a no-op on a store that was never
registered, and equally a no-op on a store that is already holding its initial state -
resetting an untouched form notifies nobody, writes nothing and adds no undo step, the same
rule every other mutation in Blex follows.
store.ResetState(); // back to the state captured at first registration
BlexManager.ResetAll() does the same across every registered store - the usual
sign-out move. Each store resets as its own action, so middleware can exempt individual
stores and DevTools shows one entry per store rather than one opaque global wipe.
@inject BlexManager Manager
// Sign-out: every store back to its registered state, each as its own action.
private void SignOut()
{
_auth.Clear();
Manager.ResetAll();
}
// Keep one store out of it with a filter veto:
builder.Services.AddBitBlexServices(options => options.UseFilter(
ctx => !(ctx.Store.Name == "theme" && ctx.ActionName == "ResetState")));When an action throws
An action is a C# method, and by default it behaves like one: what it changed before the throw stays changed - and, since it did change state, it is notified, recorded and persisted like any other action. The exception still reaches the caller and the action-error hooks.
[BlexStore(RollbackOnError = true)] makes every synchronous action a transaction
instead: a throw puts the store's fields back to what they held when the action started, and
nothing is notified, recorded, persisted or added to the undo history. Each action level is its
own transaction, so a nested action whose failure the caller catches is undone while the
caller's own changes stay.
[BlexStore(Name = "ledger", RollbackOnError = true)]
public partial class LedgerStore
{
[BlexState] private decimal _balance;
[BlexState] private IReadOnlyList<Entry> _entries = [];
[BlexAction]
private void OnWithdraw(decimal amount)
{
Balance -= amount;
Entries = [.. Entries, new Entry(-amount)];
if (Balance < 0)
throw new InvalidOperationException("Insufficient funds."); // Balance and Entries are put back
}
}
Two stores, one Withdraw each: take the money out, write the entry, then check the balance. Both start at 100.00. Withdraw 150 from each and compare what the throw leaves behind - and what it recorded.
wallet default
ledger RollbackOnError
The snapshot is a shallow copy of the [BlexState] fields - one small array per
action, no serialization - so it undoes assignments, which is how a Blex store changes, not
mutations inside an object a field points to. It covers this store only, and synchronous
actions only: an async action has already shown the UI what it changed before its first
await.
Across stores
manager.Transaction(...) is the same promise for a unit of work that spans stores: if the
body throws, every store it changed is put back the way it was when the transaction began, and the
exception reaches the caller. The actions inside run and record as usual; the putting back is one
restore, like an undo - subscriptions re-evaluate once, persistence writes the restored state back, and
the undo steps those actions recorded no longer hold what was taken back. Stores the body left alone are
not touched. Every store is serialized when it begins, so keep it for multi-store operations; like
RollbackOnError, it is synchronous only.
manager.Transaction(() =>
{
inventory.Reserve(sku, quantity);
cart.Add(sku, quantity);
wallet.Charge(price * quantity); // throws: the reservation and the cart line are taken back too
});
var order = manager.Transaction(() => checkout.PlaceOrder()); // a result, when the body has one
Each button runs one transfer inside manager.Transaction: Withdraw from the wallet, Deposit into the ledger. Whatever throws in the body - the bank declining afterwards, or the wallet's own Withdraw - puts both stores back where the transaction found them, though the wallet has no RollbackOnError of its own.
Async actions
An [BlexAction] may return Task or ValueTask. State changes
made before and after an await update the UI as they happen, but the whole
operation is recorded as a single action.
[BlexAction]
private async Task OnSaveDraft(string text)
{
IsSaving = true; // renders immediately
await _api.SaveAsync(text);
IsSaving = false; // renders again
SavedAt = DateTimeOffset.Now;
}
// Recorded once, as "SaveDraft".
ProgressStore.Run is an async [BlexAction] that moves Percent from 0 to 100 in 20 steps, 100 ms apart. Every step re-renders this page the moment it lands - count the StateChanged notifications - yet the run is recorded once, as progress/Run, when it ends.
The undo history gains one step for the whole run, and the Redux DevTools one entry carrying its
payload, { "steps": 20, "delayMilliseconds": 100 }. The render
throttling demo runs the same action faster, to show RenderInterval capping the
renders it causes.
If what you are writing is a side-effect with a loading and error lifecycle, reach for
[BlexEffect] instead - it generates all of that for you.
An async action is recorded when it ends, with what its own body changed - across its awaits, and
nothing else. A click handled while it awaits, another action of the same store, a second run of
it started meanwhile: each is recorded as an action of its own (an assignment as its own
Set X, offered to the filters like any other), in the order they finish. Only an
action dispatched from inside its body is part of it. Rollback is synchronous only:
RollbackOnError leaves an async action alone and Transaction takes a
synchronous body, since an async action has already shown the UI what it changed before its first
await.
An async void action cannot be awaited or recorded correctly, so it is a
hard error (BLEX010). Return Task or ValueTask.
An action may return a value too - T, Task<T> or
ValueTask<T> - and the wrapper hands it back (an action that creates something
can return its id). A vetoed action never runs, and its wrapper returns default.
What a dispatch actually does
- Runs every middleware's
BeforeAction. If one callsCancel(), the action stops here - nothing mutates. - Opens the action for the current flow, then runs your method body. Actions dispatched from inside it are part of it; an action started elsewhere meanwhile is its own.
- On completion, invalidates computed values and raises
StateChangedonce. - Records the action: middleware
OnActionhooks run, then DevTools receives it, then subscribers.
The global state snapshot attached to an action is captured lazily, on first access. Observers that never read it - persistence, for instance - never pay to serialize the whole tree. When nothing at all is observing, the recording step is skipped outright.