Ducky Docs
Other guides pages

Migrating from TheBlazorState

TheBlazorState keeps state in generated partial properties: [Persist] on a component property, [Shared] on a property of a POCO in DI. In Ducky 2.0 that state moves into the store: a persisted property becomes a field of a slice state, a shared POCO a SliceStore<TState>, and the configuration moves from ConfigureState to the registration.

Every snippet on this page comes from the compiled sample in docs/migration/samples/theblazorstate. Before builds against TheBlazorState and its generators: TheBlazorState was never published to nuget.org, so the sample uses a verbatim copy of its source in docs/migration/samples/legacy. After is the same app on Ducky 2.0, and After.Tests holds its tests.

Checklist

  1. Replace TheBlazorState with Ducky and Ducky.Blazor, and add Ducky.Testing to test projects.
  2. Move each [Persist] property into a slice state, and register Persist<TSlice>(...) for it (see Persisted properties).
  3. Turn each LoadFrom factory into an Effect<StoreInitialized> that checks WasRestored<TState>().
  4. Turn each [Shared] POCO into a SliceStore<TState> (see Shared state).
  5. Add a JsonSerializerContext with the persisted state types and pass it with UseJson(AppJson.Default): persistence and the prerender handoff serialize through it.
  6. Replace AddTheBlazorState with AddDucky (see Registration), then run the app's tests.

Before and after

Persisted properties

Dashboard.csfrom a tested file
// TheBlazorState: a [Persist] partial property of the component, configured in ConfigureState. LoadFrom runs when
// nothing was restored; KeySuffix scopes the key to the user, read once when the component initializes.
public sealed partial class Dashboard : ComponentBase
{
    [Inject]
    public required IStatsApi Api { get; set; }

    [Inject]
    public required ICurrentUser User { get; set; }

    [Persist(TimeToLive = "00:05:00")]
    public partial DashboardData? Stats { get; set; }

    partial void ConfigureState(__StateContext ctx) =>
        ctx.Stats
            .KeySuffix(User.Id)
            .LoadFrom(async () => (DashboardData?)await Api.GetDashboardAsync(User.Id));

    public bool FromCache => StatsMeta.WasRestored;

    protected override void BuildRenderTree(RenderTreeBuilder builder) => builder.AddContent(0, Stats?.OpenTasks);
}
Dashboard.csfrom a tested file
// Ducky 2.0: the persisted property is a field of a slice state; Persist<DashboardSlice> in the registration sets the TTL.
public sealed record DashboardState(DashboardData? Stats);

public sealed record StatsLoaded(DashboardData Stats);

public sealed class DashboardSlice : Slice<DashboardState>
{
    public DashboardSlice() => On<StatsLoaded>((state, action) => state with { Stats = action.Stats });

    protected override DashboardState Initial => new(Stats: null);
}

LoadFrom becomes an effect on StoreInitialized. It runs once, when the store is ready, after storage was read, and loads only when nothing was restored:

Dashboard.csfrom a tested file
// Ducky 2.0: LoadFrom becomes an Effect<StoreInitialized> that loads only when storage restored nothing.
public sealed class LoadStats(IStatsApi api, ICurrentUser user) : Effect<StoreInitialized>
{
    public override async Task Handle(StoreInitialized action, EffectContext context, CancellationToken cancellationToken)
    {
        if (!context.State.WasRestored<DashboardState>())
        {
            context.Dispatch(new StatsLoaded(await api.GetDashboardAsync(user.Id, cancellationToken)));
        }
    }
}

The component reads the slice; StateMeta.WasRestored becomes State.WasRestored<T>():

Dashboard.csfrom a tested file
// Ducky 2.0: StatsMeta.WasRestored becomes State.WasRestored<T>(), on the store's snapshot.
public sealed class Dashboard : DuckyComponent<DashboardState>
{
    public bool FromCache => Store.State.WasRestored<DashboardState>();

    protected override void BuildRenderTree(RenderTreeBuilder builder) => builder.AddContent(0, State.Stats?.OpenTasks);
}

Shared state

AppState.csfrom a tested file
// TheBlazorState: a [Shared] POCO registered in DI; every component that injects it re-renders when a property changes.
public sealed partial class AppState
{
    [Shared]
    public partial string? UserName { get; set; }
}
AppStore.csfrom a tested file
// Ducky 2.0: the [Shared] POCO becomes a SliceStore; its setters are Set methods. Components inject it and Select its state.
public sealed record AppState(string? UserName);

public sealed class AppStore : SliceStore<AppState>
{
    protected override AppState Initial => new(UserName: null);

    public void SetUserName(string? name) => Set(state => state with { UserName = name });
}

The injected AppStore is the store's own slice, so every component shares it. Its State is a point-in-time read: markup that must follow changes selects it (Select((AppState s) => s.UserName) in a DuckyComponent's OnInitialized, or <DuckySelect>). See SliceStore.

Registration

Registration.csfrom a tested file
// TheBlazorState: the library's services with [Persist] properties in localStorage (the prerender handoff always
// runs too), then each [Shared] POCO.
services.AddTheBlazorState(o => o.DefaultStorage = StorageStrategy.LocalStorage());
services.AddScoped<AppState>();
Registration.csfrom a tested file
// Ducky 2.0: one builder. Scope replaces KeySuffix and is resolved again when the user changes; Prerender replaces
// the PersistentComponentState bridge.
services.AddDucky(ducky => ducky
    .AddDuckyGenerated_TheBlazorState_After()
    .UseJson(AppJson.Default)
    .AddBlazor(o => o.Scope = (provider, _) => ValueTask.FromResult<string?>(provider.GetRequiredService<ICurrentUser>().Id))
    .Persist<DashboardSlice>(o => o.MaxAge = TimeSpan.FromMinutes(5))
    .Prerender<DashboardSlice>());

BlazorOptions.Scope replaces KeySuffix. It applies to every persisted key, and it is resolved again when the user changes instead of being frozen when the component initializes. A null scope means no reads and no writes for those keys, never a shared key.

Mapping table

TheBlazorState Ducky 2.0
[Persist(TimeToLive = ttl)] partial property of a component, with a LocalStorage(), SessionStorage() or ServerMemoryCache() strategy a field of a slice state, plus Persist<TSlice>(o => o.MaxAge = ttl) and Prerender<TSlice>() (TheBlazorState always ran the prerender handoff too)
[Persist] property on the default strategy (DefaultStorage is StorageStrategy.PrerenderHtml()) a field of a slice state, plus Prerender<TSlice>() alone: nothing was ever written to browser storage
[Shared] POCO a SliceStore<TState> whose setters are Set methods
ConfigureState + LoadFrom(factory) an Effect<StoreInitialized> that loads when context.State.WasRestored<TState>() is false
KeySuffix(...) BlazorOptions.Scope (re-resolved on user change, not frozen)
StateMeta.WasRestored State.WasRestored<T>()
StorageStrategy.LocalStorage(), SessionStorage(), ServerMemoryCache() PersistOptions.Storage = PersistStorage.Local, Session or Server
StorageStrategy.PrerenderHtml(), the PersistentComponentState bridge Prerender<TSlice>()
CrossTabHub no equivalent (rejected: it could leak state across users)
StorageStrategy.IndexedDb() (IndexedDbStrategy) not in 2.0; it comes in 2.1
AddTheBlazorState() AddDucky(d => d.AddBlazor())