Migrating from BlazorMVU
BlazorMVU keeps a model inside each component and updates it with one Update(msg, model) function. In Ducky 2.0 the model is a slice state in the app store, each message an action, and commands and subscriptions are effects.
Every snippet on this page comes from the compiled sample in docs/migration/samples/blazormvu. Before builds against BlazorMVU: BlazorMVU was never published to nuget.org, so the sample uses a verbatim copy of its source in docs/migration/samples/legacy/BlazorMVU.Core. After is the same app on Ducky 2.0, and After.Tests holds its tests.
Checklist
- Replace BlazorMVU with
DuckyandDucky.Blazor, and addDucky.Testingto test projects. - Turn the model into a slice state and each message into a plain action record (see Model and messages).
- Turn
InitintoInitialand each case ofUpdateinto oneOn<Msg>. - Move each
Cmdinto an effect, and eachSubinto a long-running effect. - Derive the component from
DuckyComponent<TState>, register withAddDucky(see Components and registration), then run the app's tests.
Before and after
Model and messages
// BlazorMVU: the model and its messages belong to one component.
public sealed record CounterModel(int Count, bool IsLoading, string? Error, int Seconds);
public abstract record CounterMsg
{
public sealed record Increment : CounterMsg;
public sealed record Decrement : CounterMsg;
public sealed record Load : CounterMsg;
public sealed record Loaded(int Count) : CounterMsg;
public sealed record LoadFailed(string Error) : CounterMsg;
public sealed record Tick : CounterMsg;
}// Ducky 2.0: the model is a slice state and each message a plain action record, shared by the whole app.
public sealed record CounterState(int Count, bool IsLoading, string? Error, int Seconds);
public sealed record Increment;
public sealed record Decrement;
public sealed record LoadCount;
public sealed record CountLoading;
public sealed record CountLoaded(int Count);
public sealed record CountFailed(string Error);
public sealed record Tick;Init and Update
// BlazorMVU: Init gives the first model; one Update switch handles every message.
protected override CounterModel Init() => new(Count: 0, IsLoading: false, Error: null, Seconds: 0);
protected override CounterModel Update(CounterMsg msg, CounterModel model) => msg switch
{
CounterMsg.Increment => model with { Count = model.Count + 1 },
CounterMsg.Decrement => model with { Count = model.Count - 1 },
CounterMsg.Loaded loaded => model with { Count = loaded.Count, IsLoading = false },
CounterMsg.LoadFailed failed => model with { IsLoading = false, Error = failed.Error },
CounterMsg.Tick => model with { Seconds = model.Seconds + 1 },
_ => model,
};// Ducky 2.0: Init becomes Initial, and each case of the Update switch one On<Msg>.
public sealed class CounterSlice : Slice<CounterState>
{
public CounterSlice()
{
On<Increment>(state => state with { Count = state.Count + 1 });
On<Decrement>(state => state with { Count = state.Count - 1 });
On<CountLoading>(state => state with { IsLoading = true, Error = null });
On<CountLoaded>((state, loaded) => state with { Count = loaded.Count, IsLoading = false });
On<CountFailed>((state, failed) => state with { IsLoading = false, Error = failed.Error });
On<Tick>(state => state with { Seconds = state.Seconds + 1 });
}
protected override CounterState Initial => new(Count: 0, IsLoading: false, Error: null, Seconds: 0);
}Commands
// BlazorMVU: Cmd.OfTask runs the I/O and maps its result (or its exception) to a message.
protected override (CounterModel Model, Cmd<CounterMsg> Cmd) UpdateWithCmd(CounterMsg msg, CounterModel model) =>
msg is CounterMsg.Load
? (model with { IsLoading = true, Error = null }, Cmd.OfTask<CounterMsg>(LoadAsync))
: (Update(msg, model), Cmd.None<CounterMsg>());
private async Task<CounterMsg> LoadAsync(CancellationToken cancellationToken)
{
try
{
return new CounterMsg.Loaded(await Api.GetCountAsync(cancellationToken));
}
catch (HttpRequestException exception)
{
return new CounterMsg.LoadFailed(exception.Message);
}
}// Ducky 2.0: Cmd.OfTask becomes an effect; ctx.Run dispatches started, then succeeded or failed.
public sealed class LoadCountEffect(ICounterApi api) : Effect<LoadCount>
{
public override Concurrency Policy => Concurrency.Switch; // a new LoadCount cancels the running one
public override Task Handle(LoadCount action, EffectContext context, CancellationToken cancellationToken) =>
context.Run(
started: new CountLoading(),
work: api.GetCountAsync,
succeeded: count => new CountLoaded(count),
failed: exception => new CountFailed(exception.Message),
cancellationToken);
}ctx.Run covers the started/succeeded/failed triad: any exception other than the run's own cancellation dispatches failed. The reducer no longer starts the work; the effect reacts to LoadCount after it was reduced, and Policy decides what a second LoadCount does while one runs (see Effects).
Subscriptions
// BlazorMVU: Sub.Every ticks while the component lives.
protected override Sub<CounterMsg> Subscriptions(CounterModel model) =>
Sub.Every<CounterMsg>(TimeSpan.FromSeconds(1), new CounterMsg.Tick(), "clock");// Ducky 2.0: Sub.Every becomes a LongRunning effect started at init, on the store's TimeProvider (fake in tests).
public sealed class ClockEffect : Effect<StoreInitialized>
{
public static readonly TimeSpan Interval = TimeSpan.FromSeconds(1);
public override bool LongRunning => true; // it never finishes: WhenIdleAsync doesn't wait for it
public override async Task Handle(StoreInitialized action, EffectContext context, CancellationToken cancellationToken)
{
using var timer = new PeriodicTimer(Interval, context.Time);
while (await timer.WaitForNextTickAsync(cancellationToken))
{
context.Dispatch(new Tick());
}
}
}The effect waits on context.Time, so a test drives it with TestStore.Time (a FakeTimeProvider). With Ducky.Reactive installed, a ReactiveEffect over Observable.Interval(period, timeProvider) does the same.
Components and registration
public void Increment() => Dispatch(new CounterMsg.Increment());
public void Reload() => Dispatch(new CounterMsg.Load());
protected override void BuildRenderTree(RenderTreeBuilder builder) => builder.AddContent(0, State.Count);// Ducky 2.0: the component renders the slice and dispatches to the store; DevTools replaces the time-travel debugger.
public sealed class Counter : DuckyComponent<CounterState>
{
public void Increment() => Dispatch(new Increment());
public void Reload() => Dispatch(new LoadCount());
protected override void BuildRenderTree(RenderTreeBuilder builder) => builder.AddContent(0, State.Count);
}// Ducky 2.0: the slice and both effects come from the generated registration.
services.AddDucky(ducky => ducky
.AddDuckyGenerated_BlazorMvu_After()
.AddBlazor());Mapping table
| BlazorMVU | Ducky 2.0 |
|---|---|
MvuComponent<TModel, TMsg> |
a Slice<TState> for the model, and a DuckyComponent<TState> that renders it |
Init(), InitWithCmd() |
Initial; the initial command becomes an Effect<StoreInitialized> |
an Update(msg, model) switch, UpdateWithCmd |
one On<Msg> per case; the command part becomes an effect |
Dispatch(msg), DispatchAsync(msg) |
Dispatch(action), DispatchAsync(action) (on the component, the store or an effect's context) |
Cmd.OfTask, Cmd.OfTaskUnit, the Cmd<TMsg>.OfTaskOption case |
an Effect<Msg>, with ctx.Run for the started/succeeded/failed triad |
Cmd.OfMsg, Cmd.OfFunc, Cmd.Batch |
a synchronous ctx.Dispatch in an effect, once per message |
Cmd.OfEffect |
an effect that runs the side effect and dispatches nothing |
Cmd.Delay, Cmd.DelayMsg |
an effect that awaits Task.Delay(delay, ctx.Time, cancellationToken), then dispatches |
Sub.Timer, Sub.Every |
a ReactiveEffect with Observable.Interval(period, timeProvider), or a LongRunning polling effect |
SimpleMvuComponent<TModel, TMsg> local state |
a slice (global), or plain component fields where it is truly local |
Middleware.Debounce, Middleware.Throttle |
an Effect with Switch + ctx.Time, or an Rx Debounce |
Middleware.Logger, Middleware.Timing, Middleware.ErrorHandler |
ILogger, ActivitySource and Meter; an effect on ReducerFailed or EffectFailed |
TimeTravelDebugger, EnableTimeTravel |
Redux DevTools (UseDevTools()) |