# SliceStore

A `SliceStore<TState>` is a slice with methods: components and effects call `cart.Add(line)` instead of dispatching an action. It is still a slice, with a key, reducers and every pipeline step (middleware, persistence, DevTools, effects).

Source: https://github.com/phmatray/Ducky/blob/v2/test/Ducky.Docs.Tests/Core/SliceStoreGuideTests.cs#L8-L29

```csharp
public sealed record CartLine(string Sku, int Quantity);

public sealed record Cart(ImmutableList<CartLine> Lines);

public sealed record CheckedOut;

public sealed class CartStore : SliceStore<Cart> // key "cart"
{
    public CartStore() => On<CheckedOut>(_ => Initial); // still a slice: it reacts to actions

    protected override Cart Initial => new([]);

    public int Count => State.Lines.Count; // a point-in-time read

    public void Add(CartLine line) => Set(cart => cart with { Lines = cart.Lines.Add(line) }); // DevTools: "cart/Add"

    public void Remove(string sku) => Set(cart => cart with { Lines = cart.Lines.RemoveAll(line => line.Sku == sku) });

    public void Replace(ImmutableList<CartLine> lines) => Set(cart => cart with { Lines = lines });

    public Task<DispatchResult> ClearAsync() => SetAsync(_ => Initial);
}
```

- `Set(mutator)` dispatches the change through the store. The mutator runs when the change is reduced, against the latest state, so concurrent calls never lose an update. Like a reducer, it must be pure, and returning the same reference commits nothing.
- DevTools names the change `{key}/{method}`: `cart/Add`.
- `SetAsync(mutator)` returns the `DispatchResult`, once the change is reduced.
- `State` is a point-in-time read, not a subscription. To follow changes, select.

## Use it

`AddSlice<CartStore>()` (or `AddDuckyGenerated_{Assembly}()`) registers `CartStore` as the store-owned instance, so you inject it:

Source: https://github.com/phmatray/Ducky/blob/v2/test/Ducky.Docs.Tests/Core/SliceStoreGuideTests.cs#L62-L69

```csharp
var cart = services.GetRequiredService<CartStore>(); // @inject CartStore Cart in a component
using var lineCount = store.Select((Cart state) => state.Lines.Count);

cart.Add(new CartLine("duck-yellow", Quantity: 2));
cart.Add(new CartLine("duck-blue", Quantity: 1));
cart.Remove("duck-yellow");
var shown = lineCount.Value;            // 1
var result = await cart.ClearAsync(); // Reduced, and the cart is empty
```

In a Blazor component, inherit `DuckyComponent`, `@inject CartStore Cart`, select in `OnInitialized` and call `Cart.Add(...)` from event handlers. A component that only renders `Cart.Count` re-renders after its own events only, and misses changes made elsewhere.

## Work that needs a service

A SliceStore has a parameterless constructor and never awaits. Loading, saving and calling APIs belong in an effect that injects the service and the SliceStore:

Source: https://github.com/phmatray/Ducky/blob/v2/test/Ducky.Docs.Tests/Core/SliceStoreGuideTests.cs#L39-L48

```csharp
public interface ICartApi
{
    Task<ImmutableList<CartLine>> LoadAsync(CancellationToken cancellationToken);
}

public sealed class LoadCartEffect(ICartApi api, CartStore cart) : Effect<StoreInitialized>
{
    public override async Task Handle(StoreInitialized action, EffectContext context, CancellationToken cancellationToken) =>
        cart.Replace(await api.LoadAsync(cancellationToken));
}
```

An `Effect<StoreInitialized>` runs once, when the store is initialized. Inside an effect run, `Set` follows the run's rules: once a `Switch` run is superseded, its `Set` calls are dropped, as its `context.Dispatch` calls are.
