# Step 6: Search, and effects that overlap

## What you will build in this step

A search box above the shelf. Each keystroke asks the server which ducks match, and the box says what is happening: "Searching for “yel”…", then "2 ducks match." The shelf itself starts following the search in step 7.

## Why

Type `y`, `e`, `l` quickly, and three searches are on their way: "y", "ye" and "yel". The server answers each one when it is ready, not in the order they were sent. Here, a short term matches more ducks and takes the fake server longer: "y" answers last. If every answer were applied, the last one to arrive, the answer to "y", would win, and the box would show three ducks for "yel".

An effect's **concurrency policy** decides what happens when its action arrives while an earlier run of the same effect is still going. For a search box, the newest search is the only one that matters.

## A fake search server

Create `Shop/SearchApi.cs`. This is the whole file:

Source: https://github.com/phmatray/Ducky/blob/v2/docs/tutorial/samples/DuckShop/Shop/SearchApi.cs#L2-L32

```csharp
using System.Collections.Immutable;

namespace DuckShop;

// Searching happens on the server, like the catalogue: it answers with the ids that match.
public interface ISearchApi
{
    Task<ImmutableList<string>> SearchAsync(string term, CancellationToken cancellationToken);
}

public sealed class FakeSearchApi(TimeProvider time) : ISearchApi
{
    // A short term matches more ducks, so the fake server takes longer to answer it:
    // "y" takes 600 ms, "ye" 450 ms, "yel" 300 ms. Typing fast leaves older, slower
    // searches still running when the newest one answers.
    public static TimeSpan Latency(string term) =>
        TimeSpan.FromMilliseconds(Math.Max(150, 750 - (150 * term.Length)));

    public async Task<ImmutableList<string>> SearchAsync(
        string term,
        CancellationToken cancellationToken)
    {
        await Task.Delay(Latency(term), time, cancellationToken);
        return
        [
            .. FakeCatalogueApi.Ducks
                .Where(duck => duck.Name.Contains(term, StringComparison.OrdinalIgnoreCase))
                .Select(duck => duck.Id),
        ];
    }
}
```

Register it in `Program.cs`, below the catalogue's registration:

Source: https://github.com/phmatray/Ducky/blob/v2/docs/tutorial/samples/DuckShop/Program.cs#L21-L21

```csharp
builder.Services.AddSingleton<ISearchApi, FakeSearchApi>();
```

## The search slice

Create `Shop/Search.cs`, with the search state, its two actions and the slice:

Source: https://github.com/phmatray/Ducky/blob/v2/docs/tutorial/samples/DuckShop/Shop/Search.cs#L2-L28

```csharp
using System.Collections.Immutable;
using Ducky;

namespace DuckShop;

// What the box shows (Query), whether a search is running, and the ids that matched.
// Hits is null when there is no search: the shelf then shows every duck.
public sealed record SearchState(string Query, bool Searching, ImmutableList<string>? Hits);

[DuckyAction]
public sealed record TypeSearch(string Query);

public sealed record SearchAnswered(ImmutableList<string> Hits);

public sealed class SearchSlice : Slice<SearchState>
{
    public SearchSlice()
    {
        On<TypeSearch>((state, action) => string.IsNullOrWhiteSpace(action.Query)
            ? new SearchState(action.Query, Searching: false, Hits: null)
            : state with { Query = action.Query, Searching = true });
        On<SearchAnswered>((state, action) =>
            state with { Searching = false, Hits = action.Hits });
    }

    protected override SearchState Initial => new("", Searching: false, Hits: null);
}
```

`TypeSearch` is dispatched by the search box, so it has `[DuckyAction]` and a `TypeSearch(...)` helper; `SearchAnswered` comes from the effect only.

## The effect, with Switch

Add the effect at the end of `Shop/Search.cs`:

Source: https://github.com/phmatray/Ducky/blob/v2/docs/tutorial/samples/DuckShop/Shop/Search.cs#L32-L51

```csharp
public sealed class SearchEffect(ISearchApi api) : Effect<TypeSearch>
{
    // Switch: a new keystroke cancels the search still running, and a cancelled run's
    // actions are dropped. Only the newest term ever answers.
    public override Concurrency Policy => Concurrency.Switch;

    public override async Task Handle(
        TypeSearch action,
        EffectContext context,
        CancellationToken cancellationToken)
    {
        if (string.IsNullOrWhiteSpace(action.Query))
        {
            return; // an empty box needs no search; this run still cancels the previous one
        }

        var hits = await api.SearchAsync(action.Query.Trim(), cancellationToken);
        context.Dispatch(new SearchAnswered(hits));
    }
}
```

`Concurrency.Switch` cancels the run still going when a new `TypeSearch` arrives, and starts the new one. A cancelled run's `cancellationToken` is cancelled, so its server call stops waiting, and anything it would still dispatch is dropped. Only the run for the newest term can dispatch `SearchAnswered`. The four policies:

| Policy | A new action while a run is going | Use it for |
|---|---|---|
| `Merge` (the default) | starts another run; both go on | independent work, such as one save per item |
| `Switch` | cancels the running one; the newest wins | search boxes, "load the selected item" |
| `Exhaust` | starts no run until the running one finishes (the action is still reduced) | a submit button: a double click pays once |
| `Queue` | waits for the running one, then starts | work that must happen in order |

## The search box

Create `Components/SearchBox.razor`. This is the whole file:

Source: https://github.com/phmatray/Ducky/blob/v2/docs/tutorial/samples/DuckShop/Components/SearchBox.razor#L2-L28

```razor
@inherits DuckyComponent

<div class="search">
  <input type="search" value="@_search.Value.Query" @oninput="OnInput"
         placeholder="Search the ducks" aria-label="Search the ducks" />
  <p class="status" aria-live="polite">@StatusText</p>
</div>

@code {
  private Selection<SearchState> _search = null!;

  private string StatusText => _search.Value switch
  {
    { Searching: true } search => $"Searching for “{search.Query.Trim()}”…",
    { Hits: { Count: 0 } } => "No duck matches.",
    { Hits: { Count: 1 } } => "1 duck matches.",
    { Hits: { } hits } => $"{hits.Count} ducks match.",
    _ => "",
  };

  protected override void OnInitialized() =>
    _search = Select((SearchState search) => search);

  // Every keystroke dispatches TypeSearch; the effect's Switch policy decides which
  // search is still worth answering.
  private void OnInput(ChangeEventArgs e) => Store.TypeSearch(e.Value as string ?? "");
}
```

The box dispatches on every keystroke. It doesn't wait, debounce or cancel anything itself: that is the effect's policy.

Put the box on top of the shelf: in `Components/Shelf.razor`, add this line below `@inherits DuckyComponent`:

Source: https://github.com/phmatray/Ducky/blob/v2/docs/tutorial/samples/DuckShop/Components/Shelf.razor#L6-L6

```razor
<SearchBox />
```

## Run it

Reload the page, then type `yel` quickly in the search box. It says **Searching for “yel”…**, then, about 300 ms later, **2 ducks match.** (Classic Yellow and Mellow Yellow). The answers to "y" and "ye" never show, though the fake server takes longer for them. Clear the box: the status line empties. The shelf still shows all six ducks; step 7 changes that.

The sample's [SearchTests.cs](https://github.com/phmatray/Ducky/blob/v2/docs/tutorial/samples/DuckShop.Tests/SearchTests.cs) types `y`, `ye`, `yel` on a fake clock: with `Switch`, one `SearchAnswered` arrives, with the two matches for "yel". The same effect with `Merge` gets three answers, and the last one, for "y", leaves three ducks for "yel".

## Checkpoint

- Why would `Merge` be wrong here? (Every search would run to the end and dispatch its answer; the slowest one, an old term, would arrive last and win.)
- What happens to a run that `Switch` cancels? (Its token is cancelled and anything it dispatches afterwards is dropped.)
- Which policy fits a "Pay" button? (`Exhaust`: clicks during a payment start no second payment.)

## Common mistake

**Keeping the default policy.** Without `public override Concurrency Policy => Concurrency.Switch;` the effect runs with `Merge`. Nothing warns: the search works when you type slowly and shows the wrong ducks when you type fast, the bug in the "Why" above. Fix: pick the policy for each effect on purpose. A related slip is not passing `cancellationToken` to the server call: `Switch` still drops the old run's answer, but the old request keeps running to the end for nothing.

Next: [Step 7: Derived data with a selector](07-selectors.md).
