Vibe coding with Claude Code course · Module 11: Spotify clone

Search and Recommendations: Scout First, Change Later

9 min read
In this lesson10

The Sea Shanty Sounds catalog keeps growing and nobody will scroll through hundreds of shanties to find the one about the kraken. The crew needs a search with tabs and a small "Similar" box that suggests something in the same mood. The project already has two lessons of code behind it, so before Claude changes anything it must know what is already there. An agent that does not check this happily creates a second copy of the data in a new file or calls functions nobody wrote.

What you will learn

  • send the Explore subagent to scout before Claude changes code;
  • read a search with a 300 ms delay that cleans up after itself;
  • check that an older server response cannot overwrite a newer one;
  • make sure every tab has its own section or an empty state.

Scouting with Explore

You know the built-in Explore subagent from lesson 5_4. The Claude Code documentation describes it as a helper for finding files and reading code that has only read tools (Write and Edit are blocked for it) and starts without your CLAUDE.md, so the scouting is quick and cheap. It is a different tool from /btw in lesson 10_1. The documentation puts it briefly: with /btw you ask about what Claude already knows from the conversation, and you send a subagent to find out something new.

Request for Claude Code (scouting):

Use the Explore subagent. Do not change any files. Before we add
a search, find out: where the catalog data lives (tracks, albums,
artists, playlists) and which files import it, whether the project
already has a function that formats time or compares text, which types
describe a track, an album, an artist and a playlist. Answer in
5 points, with a file path in each.

You check the report in Cursor before you order anything. After lessons 10_1 and 10_2 the data lives in one file, lib/catalog.ts, and it is imported by three pages: app/page.tsx, app/playlists/page.tsx and app/playlists/[id]/page.tsx, plus the tests. Search the project (Cmd+Shift+F on a Mac, Ctrl+Shift+F on Windows) for lib/catalog and compare the hits with the report. A report that skips a file or names a file that does not exist goes back with a request for a correction. A good report also mentions formatTime in lib/format.ts, and says that a function for comparing text does not exist.

Request for Claude Code (build):

Based on the scouting, add a search. lib/search.ts: searchCatalog
on the data from @lib/catalog.ts, no second copy of the data, no
accents ("cafe" finds "Café"). A Route Handler app/api/search,
components/SearchPage.tsx and the page /search: a field with a 300 ms
delay and the tabs All, Tracks, Albums, Artists, Playlists.
Done when:
1. a fast typing of "shan" sends the server one request;
2. an older response does not overwrite a newer one (a test with
   a fake fetch);
3. every tab shows its own section or a note about no results;
4. lint, types, tests and build pass. Show the commands and results.

Condition 2 describes a classic race. You type "hymn", the server starts searching, you change your mind to "kraken". If the first response arrives later than the second, the screen keeps the results for "hymn" while the field says "kraken".

What Claude wrote: search without accents

Open lib/search.ts in Cursor. The text from the field and the text from the catalog go through the same function:

export function normalize(text: string): string {
  return text
    .toLowerCase()
    .replace(/ł/g, "l")
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "");
}

normalize("NFD") splits a letter with an accent into the letter and a separate accent mark, and the last line removes those marks. The letter "ł" does not split this way, which is why it stands on its own at the start: Polish names turn up in a sailors' catalog too. In our run the test returned "cafe" for "Café" and "lukasz" for "Łukasz". searchCatalog always returns all four lists, empty ones too: for "shan" one track, one playlist and two empty lists of albums and artists.

What Claude wrote: 300 ms and cleanup

Open components/SearchPage.tsx. The delay, called a debounce, is a timer that waits until you have stopped typing for 300 ms and only then asks the server:

useEffect(() => {
  if (!q) return;
  const controller = new AbortController();
  const timer = setTimeout(async () => {
    try {
      const res = await fetch(`/api/search?q=${encodeURIComponent(q)}`, { signal: controller.signal });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      setResult({ query: q, data: await res.json() });
    } catch {
      if (!controller.signal.aborted) setResult({ query: q, data: null });
    }
  }, 300);
  return () => {
    clearTimeout(timer);
    controller.abort();
  };
}, [q]);

q is the text from the field without spaces at the ends, so a space added at the end sends no new request. Every letter changes q, and before running the effect again React calls the cleanup of the previous one. The cleanup does two things for two different moments. clearTimeout cancels a timer that is still waiting, so letters typed faster than every 300 ms never reach the server. abort() cancels a request that has already left: according to MDN, fetch then ends with an AbortError, and the condition in catch does not treat it as a failure. setResult sits in the timer function, not directly in the body of the effect, so the react-hooks/set-state-in-effect lint rule from earlier locations has no objections.

What Claude wrote: the result matches the question

The result remembers what it was asked, and the "Searching..." note comes from a comparison, with no separate loading state:

const current = q && result?.query === q ? result : null;

If the field says "kraken" and the last result is for "hymn", current is empty and the page shows "Searching...". data: null in the result means the request failed, and then a message asking for another try appears.

What Claude wrote: tabs you cannot lose

Each section has its own drawing function in one object:

const RENDER: Record<Section, (r: SearchResults) => React.ReactNode> = {
  tracks: (r) => r.tracks.map((t) => <li key={t.id}>{t.title}, {t.artist.name}</li>),
  albums: (r) => r.albums.map((a) => <li key={a.id}>{a.title} ({a.year})</li>),
  artists: (r) => r.artists.map((a) => <li key={a.id}>{a.name}</li>),
  playlists: (r) => r.playlists.map((p) => <li key={p.id}>{p.name}</li>),
};

Section is a union of the four section names, and Record demands a function for each of them, like the layout labels of the duet in lesson 9_3. For us deleting the albums line ended with the error TS2741 reading Property 'albums' is missing in type. The All tab draws four sections, every other tab draws one. A section with an empty list shows "No results in this category.", so a click on Albums with "shan" gives a note, not an empty page.

What Claude wrote: similar shanties

Under the player stands a "Similar" box. Our clone does not pretend to have the algorithms of big services: recommendations are one explicit rule in lib/recommend.ts that you can test:

export function similarTracks(track: Track, catalog: Track[], limit = 3): Track[] {
  return catalog
    .filter((t) => t.genre === track.genre && t.id !== track.id)
    .slice(0, limit);
}

The rule reads: tracks of the same genre, without the one that is playing, at most three. The order matters: filter first, then slice, because the other way round the catalog would give the first three tracks of any genre. For us "Kraken's Song" is the only ballad, so the test got an empty list and the box showed "No other tracks in the ballad genre.".

Captain's review

  1. A tab without a section. A typical agent mistake is two conditions, tab === "tracks" and tab === "artists", instead of five, because it copied two cases out of five. For us that version passed lint and tsc. The test from condition 3 failed: Unable to find an accessible element with the role "region" and name "Albums". Type "shan" and click every tab.
  2. The response race. The version without controller.abort() passed lint and tsc, and the test from condition 2 reported Unable to find an element with the text: Kraken's Song, Black Mary: a late response for "hymn" overwrote the result for "kraken", and the page got stuck on "Searching...". Search the file for clearTimeout( and abort(: both must sit in the return of the effect.
  3. One copy of the data. Search the project for mock and [...]. An agent without scouting may call mockTracks and mockAlbums, which nobody defined, or leave tracks: [...] where the data should be. After scouting, the data has one source, lib/catalog.ts.
  4. Proof in the browser. Open /search, go to the Network tab in the developer tools and type "shan" fast. For us one request went out, q=shan.

Next step

Before the commit run /code-review from lesson 2_9: a reviewer in a fresh subagent did not see how the effect came to be, so it looks at it without your shared reasoning. You check every finding like a hypothesis before you ask for a fix with a narrow request. The search and the "Similar" box share no files, so on a bigger ship they could be built in parallel in two worktrees, as in lesson 9_2. When the review and the tests agree, ask for a commit, for example "Search and similar shanties".

In the editor below a search is waiting, with a fake server that answers shorter queries more slowly. Type "kr", wait half a second, add "aken" and watch the request log. Then turn on the bug without abort() and repeat it, and finally the bug with two sections instead of four, and click the Albums tab.

Remember: a captain first sends a scout ashore and only then the landing party, and a catalog without an "Albums" tab is a map without the island you are sailing to.

Code for this lesson: App.jsx
// Search in miniature: the fake server answers shorter queries more slowly
import { useEffect, useState } from 'react';

const catalog = {
  tracks: [
    { id: 't1', title: 'Pirate Hymn', artist: 'Captain Redbeard' },
    { id: 't2', title: 'Battle Drums', artist: 'Black Mary' },
    { id: 't3', title: 'Island Shanty', artist: 'Captain Redbeard' },
    { id: 't4', title: "Kraken's Song", artist: 'Black Mary' },
  ],
  albums: [
    { id: 'al1', title: 'Songs from the Deck', year: 1718 },
    { id: 'al2', title: 'Storm over Tortuga', year: 1721 },
  ],
  artists: [
    { id: 'a1', name: 'Captain Redbeard' },
    { id: 'a2', name: 'Black Mary' },
  ],
  playlists: [{ id: 'p1', name: 'Watch Shanties' }],
};

const normalize = (text) => text.toLowerCase().replace(/ł/g, 'l').normalize('NFD').replace(/[\u0300-\u036f]/g, '');

function searchCatalog(query) {
  const q = normalize(query);
  const has = (text) => normalize(text).includes(q);
  return {
    tracks: catalog.tracks.filter((t) => has(t.title) || has(t.artist)),
    albums: catalog.albums.filter((a) => has(a.title)),
    artists: catalog.artists.filter((a) => has(a.name)),
    playlists: catalog.playlists.filter((p) => has(p.name)),
  };
}

// Fake fetch: the shorter the query, the longer it waits (1 letter: 1.5 s), and it listens for the abort signal
function fakeFetch(q, signal) {
  const delay = Math.max(200, 1750 - 250 * q.length);
  return new Promise((resolve, reject) => {
    const id = setTimeout(() => resolve(searchCatalog(q)), delay);
    signal.addEventListener('abort', () => {
      clearTimeout(id);
      reject(new DOMException('aborted', 'AbortError'));
    });
  });
}

const TABS = ['all', 'tracks', 'albums', 'artists', 'playlists'];
const SECTIONS = ['tracks', 'albums', 'artists', 'playlists'];
const LABELS = { all: 'All', tracks: 'Tracks', albums: 'Albums', artists: 'Artists', playlists: 'Playlists' };
const RENDER = {
  tracks: (r) => r.tracks.map((t) => <li key={t.id}>{t.title}, {t.artist}</li>),
  albums: (r) => r.albums.map((a) => <li key={a.id}>{a.title} ({a.year})</li>),
  artists: (r) => r.artists.map((a) => <li key={a.id}>{a.name}</li>),
  playlists: (r) => r.playlists.map((p) => <li key={p.id}>{p.name}</li>),
};

export default function App() {
  const [query, setQuery] = useState('');
  const [tab, setTab] = useState('all');
  const [result, setResult] = useState(null);
  const [log, setLog] = useState([]);
  const [noAbort, setNoAbort] = useState(false);
  const [twoSections, setTwoSections] = useState(false);
  const q = query.trim();
  const note = (line) => setLog((l) => [line, ...l].slice(0, 10));

  useEffect(() => {
    if (!q) return;
    const controller = new AbortController();
    const timer = setTimeout(async () => {
      note(`sent: ${q}`);
      try {
        const data = await fakeFetch(q, controller.signal);
        note(`response: ${q}`);
        setResult({ query: q, data });
      } catch {
        if (controller.signal.aborted) note(`aborted: ${q}`);
      }
    }, 300);
    return () => {
      clearTimeout(timer);
      if (!noAbort) controller.abort(); // agent bug: without abort() the old request keeps going
    };
  }, [q, noAbort]);

  // Without the agent bug the result must match the question; with the bug we show the last one that arrived
  const current = noAbort ? result : q && result?.query === q ? result : null;
  const data = current?.data;
  const visible = twoSections
    ? SECTIONS.filter((s) => (s === 'tracks' || s === 'artists') && (tab === 'all' || tab === s))
    : tab === 'all' ? SECTIONS : [tab];

  return (
    <div className="min-h-screen bg-gray-950 p-4 text-white">
      <div className="mx-auto max-w-xl space-y-3">
        <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Type kr, wait, add aken" className="w-full rounded-full bg-gray-800 px-4 py-2" />
        <div className="flex flex-wrap gap-2">
          {TABS.map((t) => (
            <button key={t} type="button" onClick={() => setTab(t)} className={`rounded-full px-3 py-1 text-sm ${tab === t ? 'bg-white text-black' : 'bg-gray-800'}`}>
              {LABELS[t]}
            </button>
          ))}
        </div>
        {q && !current && <p className="text-gray-400">Searching...</p>}
        {current && <p className="text-xs text-gray-400">Results for: "{current.query}", in the field: "{q}"</p>}
        {data && visible.map((s) => (
          <section key={s}>
            <h2 className="font-semibold">{LABELS[s]}</h2>
            {data[s].length === 0 ? <p className="text-sm text-gray-400">No results in this category.</p> : <ul className="text-sm">{RENDER[s](data)}</ul>}
          </section>
        ))}
        {data && visible.length === 0 && <p className="text-sm text-red-400">Empty page: this tab has no section.</p>}
        <div className="space-y-1 text-sm">
          <label className="flex items-center gap-2"><input type="checkbox" checked={noAbort} onChange={(e) => setNoAbort(e.target.checked)} /> Agent bug: no abort()</label>
          <label className="flex items-center gap-2"><input type="checkbox" checked={twoSections} onChange={(e) => setTwoSections(e.target.checked)} /> Agent bug: only Tracks and Artists</label>
        </div>
        <div className="rounded-xl bg-black p-3 font-mono text-xs text-green-400">
          <p className="text-gray-400">Request log (newest on top):</p>
          {log.map((line, i) => <p key={i}>{line}</p>)}
        </div>
      </div>
    </div>
  );
}

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Why does the search wait 300 ms before asking the server?

  2. 2. What does searchCatalog("shan") return for a category in which nothing matches?

These are 2 of 6 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Click in order

    Click the pieces to build a search request that can be aborted:

  • Click in order

    Click the pieces to build the delayed search:

  • Horizontal ordering

    Arrange in one line the choice of the result that matches the text in the field:

  • Code editor

    Search interface

  • Vertical ordering

    Arrange what happens when you add a letter in the search field:

  • Vertical ordering

    Arrange the lines of the similarTracks function:

  • Click in order

    Click the pieces to build the cleanup that cancels the waiting timer:

  • Horizontal ordering

    Arrange in one line the error handling that skips aborted requests:

  • Vertical ordering

    Arrange the steps of working on the search from the lesson:

  • Code editor

    Music discovery interface

  1. QuestionThe search delay
  2. QuestionEmpty categories in the results
  3. Click in orderA request with an abort signal
  4. Click in orderBuild the delay timer
  5. Put in orderThe result matches the question
  6. Coding taskPractice: Search page
  7. QuestionScouting with Explore
  8. QuestionThe similar shanties rule
  9. Put in orderThe delayed search flow
  10. Put in orderThe similarTracks function
  11. Click in orderBuild the timer cleanup
  12. QuestionWhy abort() in the cleanup
  13. Put in orderAn abort is not a failure
  14. Put in orderOrder of work on the search
  15. Coding taskPractice: Browse categories
  16. QuestionTabs you cannot lose

Useful articles