Vibe coding with Claude Code course · Module 5: Reddit clone
Harbor interrogation: search with the phrase in the address
In this lesson9
Yesterday you stopped on a red test for strikethrough. You open a terminal in the crew-council folder and type claude -c: Claude Code opens the last conversation from that folder, with the request and the test result. All you have to write is "Finish this: add remark-gfm until the test passes. Do not change the tests", read the diff and make a commit. Today's job is a new feature, so you start it with /clear. Why this way and not another you will see in the last lesson of this location.
Crew Council keeps getting more posts. Jack remembers that someone wrote about a wreck with gold, but he remembers neither the title nor the guild. Scrolling through hundreds of posts is not an interrogation, it is torture. You need a search that works together with guilds and sorting.
The problem: first ask how much there is
Before a word about code, answer one question: how many posts will the search go through? With a few hundred it is enough to scan the list that Feed already keeps in the browser. With hundreds of thousands, a database on a server would do the searching. An agent without that information guesses, and it often picks the grand option: a new endpoint, a full-text search library or a database you did not ask for. A number in the request saves you that detour.
The second decision: when to search. The phrase goes into the address as ?q=, next to ?community= from lesson 4_3, so that a link to the results can be sent to a shipmate. But every change of address is a request to the server for a page, which you saw in the terminal in lesson 3_5. There a debounce helped, that is, waiting to send until the typist pauses. Here it is simpler: you search on Enter, so one search means one request and no debounce is needed. Next.js has a component for this, Form from next/form: a form that on submit appends its fields to the address and navigates there without reloading the page.
Request for Claude Code
The request gathers both decisions and orders the proof right away:
Request for Claude Code:
Add post search to Crew Council. There will be a few hundred posts, so
search in the browser, on the list that @components/Feed.tsx keeps:
no database, no new endpoint and no new packages. The phrase goes
into the address as ?q= next to ?community=, and the field sends it
with Enter through Form from next/form in components/SearchBar.tsx.
Search the title and body, ignoring letter case; with several words
a post must contain every one of them. Tests first, for the function
searchPosts(posts, query) in lib/search.test.ts, including the phrase
with a bracket "(two". Run them before the code and after it.
At the end run tests, lint and build, and show the output.The request says how much data there is, where it lives and what not to add. The bracket in the test is no accident, you will see why in a moment.
What Claude wrote: the test
Open lib/search.test.ts. At the top stand three posts built with the makePost helper: a map to Skull Island, a voyage to Tortuga with a wreck in the body, and hull patching with the body "A hole above the waterline (two cubits)". Two cases out of six:
it("several words: a post must contain each of them", () => {
expect(ids(searchPosts(list, "map skull"))).toEqual(["p1"]);
expect(ids(searchPosts(list, "skull map"))).toEqual(["p1"]);
expect(ids(searchPosts(list, "map kraken"))).toEqual([]);
});
it("special characters do not break the search", () => {
expect(ids(searchPosts(list, "(two"))).toEqual(["p3"]);
});ids turns the result into a list of bare ids, so the comparison fits on one line. The first test says the order of words does not matter, and a word that is not in the post rejects it. The others check an empty phrase, capital letters, searching the body and the fact that the input list does not change. On an empty skeleton four of the six tests fail, and that is good.
The simplest version is not enough
Agents often reach for a regular expression, a pattern for searching text in which some characters have a special meaning. We checked such a version:
const pattern = new RegExp(query.trim().split(/\s+/).join(".*"), "i");
return posts.filter((post) => pattern.test(`${post.title} ${post.content}`));Words glued together with .* mean "this word, anything, then that one", and the i flag turns letter case off. The test result:
× several words: a post must contain each of them
× special characters do not break the search
SyntaxError: Invalid regular expression: /(two/i: Unterminated group
Tests 2 failed | 29 passed (31)A bracket in a pattern opens a group that nobody closed, so the function throws. On the page that would mean a white screen after typing a bracket, and the phrase "skull map" will not be found, because the pattern guards the order. On the screen with sample data everything looked fine, and the test showed both errors.
What Claude wrote: searchPosts
The version that passes uses no patterns at all:
export function searchPosts(posts: Post[], query: string): Post[] {
const words = query.toLocaleLowerCase("en").split(/\s+/).filter(Boolean);
if (words.length === 0) {
return posts;
}
return posts.filter((post) => {
const text = `${post.title} ${post.content}`.toLocaleLowerCase("en");
return words.every((word) => text.includes(word));
});
}toLocaleLowerCase("en") lowercases text by the rules of a given language. split(/\s+/) cuts the phrase into words at spaces, and filter(Boolean) throws away empty pieces, so a phrase of only spaces behaves like an empty one. every returns true when every word meets the condition, and includes looks for plain text, in which a bracket is just a bracket. An empty phrase returns the same list, and filter always builds a new one, so state does not change quietly. The result: Tests 31 passed (31).
What Claude wrote: the phrase in the address
app/page.tsx reads the phrase the way it read the guild in lesson 4_3 and passes it on:
const { community, q } = await searchParams;
const query = typeof q === "string" ? q : "";Under the heading stands <SearchBar query={query} community={selected?.id ?? null} />, and Feed gets a new query prop. Open components/SearchBar.tsx; below is its middle without the Tailwind classes and the placeholder text:
<Form action="/" role="search">
{community && <input type="hidden" name="community" value={community} />}
<input key={query} name="q" type="search" defaultValue={query} aria-label="Search posts" />
<button type="submit">Search</button>
</Form>After Enter, Form builds the address from the name attributes of the fields, for example /?community=pirate-life&q=wreck, and navigates there without reloading. The hidden community field makes you search inside the open guild. role="search" tells a screen reader this is a search. There is no state and no "use client" here, so the bar stays a Server Component. Why key is there you will see in the review.
In components/Feed.tsx one line appeared before the sorting:
const found = searchPosts(filtered, query);
const visiblePosts = sortPosts(found, sortMode);First the guild filter from lesson 4_3, then the phrase, and at the end sorting of what is left. Both filters only narrow the list and the posts state does not change, so votes and new posts survive every search. When nothing matches, Feed writes "No post matches the phrase" instead of leaving an empty page.
useMemo as a precaution
Claude likes to wrap such a filter in useMemo, a hook that remembers the result of a calculation between renders and recomputes it only when a value from its dependency list changes. The React documentation says the calculation is usually not expensive unless you are creating or looping over thousands of objects, and advises measuring it with console.time. The rule from lesson 3_5 still holds: measure first, useMemo after. When you meet useMemo in someone else's code, you already know what it does.
Captain's review
- Filtering on the server. This is the typical agent mistake:
searchPostsinapp/page.tsxand the filtered list handed toFeedasinitialPosts. We checked it. After Enter the address changes, yet the list still shows all posts; only a page refresh shows the result.useState(initialPosts)takes its starting value only on the first render, likeGalleryin lesson 3_5. On top of that, new posts from the form would never reach the results. In the diffsearchPostsmust stand inFeed. - The field after a guild change. Search for "map" and click All. The list shows all posts, and the field should be empty. Without
key={query}"map" stays in it: a field someone typed in keeps the typed text even when itsdefaultValuechanges. We checked this. A new key tells React to draw the field from scratch, with the phrase from the address. - Letters and brackets. Type "MAP", then "kraken (". The first phrase finds the map, the second shows the no-results message, with no white screen.
- Guild, phrase and state. Vote for the Tortuga post and add a post "Who sails for the wreck?" in r/PirateLife. Then enter r/PirateLife and search for "wreck". The address is
/?community=pirate-life&q=wreck, the vote and the new post are in place, and the Back button returns to the previous result.
Next step
When everything passes, ask for a commit, for example "Search: searchPosts with tests, phrase in the address". Then another small step:
Search must work without accents: "cafe" finds "Café Tortuga" and
"pawel" finds "Paweł's logbook". Test first in @lib/search.test.ts,
run it before the code and after it. Do not change the tests.Claude's first idea is to split accented letters into a letter and a mark with normalize("NFD") and strip the marks. The test fails anyway: expected [] to deeply equal [ 'p5' ]. The letter ł does not decompose into l and a stroke, so "Paweł" does not become "Pawel", even though "Café" becomes "Cafe" without trouble. The fix is one more replacement, .replace(/ł/g, "l"), and the test caught it before the first pirate noticed. When you want to highlight the words found, tell Claude to split the text into pieces and wrap the hits in a <mark> element in JSX, not to build HTML for dangerouslySetInnerHTML. In the editor below waits a search with guilds, sorting and a small searchPosts check: type a phrase with a bracket and watch the address above the list.
Remember: you begin a harbor interrogation by asking how many people to question, and a phrase saved in the address is a note that every shipmate reads from the same place.
Code for this lesson: App.jsx
// Harbor interrogation: search with guild and sorting, phrase sent with Enter
import { useState } from 'react';
const posts = [
{ id: 'p1', community: 'pirate-life', title: 'Do we sail to Tortuga or north?', content: 'In the north lies a wreck with a hold full of gold.', score: 90 },
{ id: 'p2', community: 'treasure-hunting', title: 'A map with a cross on Skull Island', content: 'I found it in a bottle.', score: 90 },
{ id: 'p3', community: 'ship-building', title: 'How to patch the hull with pitch?', content: 'A hole above the waterline (two cubits).', score: 38 },
{ id: 'p4', community: 'sea-battles', title: 'The Kraken sank our longboat', content: 'Steer clear of Mist Bay.', score: 45 },
{ id: 'p5', community: 'treasure-hunting', title: 'A second map to the same wreck?', content: 'Someone is selling it in the port.', score: 12 },
];
const communities = ['treasure-hunting', 'sea-battles', 'pirate-life', 'ship-building'];
// The same function as lib/search.ts: plain text instead of a pattern, every word must appear
function searchPosts(list, query) {
const words = query.toLocaleLowerCase('en').split(/\s+/).filter(Boolean);
if (words.length === 0) return list;
return list.filter((post) => {
const text = `${post.title} ${post.content}`.toLocaleLowerCase('en');
return words.every((word) => text.includes(word));
});
}
const ids = (list) => list.map((post) => post.id).join(',');
const checks = [
{ name: 'an empty phrase returns everything', ok: ids(searchPosts(posts, ' ')) === ids(posts) },
{ name: 'capital letters: MAP', ok: ids(searchPosts(posts, 'MAP')) === 'p2,p5' },
{ name: 'searching the body: bottle', ok: ids(searchPosts(posts, 'bottle')) === 'p2' },
{ name: 'word order: wreck second', ok: ids(searchPosts(posts, 'wreck second')) === 'p5' },
{ name: 'bracket: (two', ok: ids(searchPosts(posts, '(two')) === 'p3' },
];
export default function App() {
const [community, setCommunity] = useState('');
const [query, setQuery] = useState('');
const [sortMode, setSortMode] = useState('top');
// In the project the phrase and the guild live in the address; here we show what it would look like
const params = new URLSearchParams();
if (community) params.set('community', community);
if (query) params.set('q', query);
const address = '/' + (params.toString() ? '?' + params.toString() : '');
// First the guild, then the phrase, and at the end sorting a copy
const inCommunity = community ? posts.filter((post) => post.community === community) : posts;
const found = searchPosts(inCommunity, query);
const visible = [...found].sort((a, b) => (sortMode === 'top' ? b.score - a.score : a.title.localeCompare(b.title, 'en')));
const handleSubmit = (event) => {
event.preventDefault();
setQuery(new FormData(event.currentTarget).get('q'));
};
return (
<div className="min-h-screen bg-gray-100 p-4 text-gray-900">
<div className="mx-auto max-w-2xl space-y-3">
<h1 className="text-2xl font-bold">Crew Council: search</h1>
<form onSubmit={handleSubmit} role="search" className="flex gap-2">
<input key={query} name="q" type="search" defaultValue={query} aria-label="Search posts" placeholder="Search titles and bodies, Enter sends" className="flex-1 rounded border border-gray-300 bg-white p-2" />
<button type="submit" className="rounded bg-gray-900 px-4 text-white">Search</button>
</form>
<div className="flex flex-wrap gap-2">
<select value={community} onChange={(event) => setCommunity(event.target.value)} aria-label="Guild" className="rounded border border-gray-300 bg-white p-1">
<option value="">All guilds</option>
{communities.map((id) => <option key={id} value={id}>{id}</option>)}
</select>
{['top', 'a-z'].map((mode) => (
<button key={mode} type="button" onClick={() => setSortMode(mode)} aria-pressed={sortMode === mode} className={sortMode === mode ? 'rounded bg-orange-600 px-3 py-1 text-white' : 'rounded px-3 py-1 hover:bg-gray-200'}>
{mode}
</button>
))}
</div>
<p className="font-mono text-sm text-gray-600">Address: {address}</p>
{visible.length === 0 && <p className="text-gray-500">No post matches the phrase: {query}</p>}
{visible.map((post) => (
<article key={post.id} className="rounded-lg border border-gray-200 bg-white p-3">
<p className="text-xs text-gray-500">r/{post.community} · score {post.score}</p>
<h2 className="font-semibold">{post.title}</h2>
<p className="text-sm text-gray-700">{post.content}</p>
</article>
))}
<section className="rounded-lg bg-white p-3 text-sm">
<h2 className="mb-2 font-bold">searchPosts check</h2>
<ul className="space-y-1">
{checks.map((check) => (
<li key={check.name} className={check.ok ? 'text-green-700' : 'font-semibold text-red-700'}>
{check.ok ? 'PASSED' : 'FAILED'}: {check.name}
</li>
))}
</ul>
<p className="mt-2 text-gray-600">Swap includes for a regular expression and type a bracket: see what happens.</p>
</section>
</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. What will searchPosts from the lesson return for the phrase "skull map", when one of the posts has the title "A map with a cross on Skull Island"?
2. According to the lesson, when is it worth wrapping post filtering in useMemo?
These are 2 of 6 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Search and filter posts
- Vertical ordering
Put in order what happens after you type "wreck" in r/PirateLife and press Enter:
- Vertical ordering
You add strikethrough through remark-gfm. Put the steps of the test loop in order, from the request to the commit:
Tasks after this lesson
- QuestionQuiz: Several words in searchPosts
- Coding taskPractice: Search & filter
- QuestionQuiz: When to use useMemo when filtering
- Put in orderSorting: The journey of a search phrase
- QuestionQuiz: Where to filter search
- QuestionQuiz: key on the search field
- Put in orderSorting: Test first, then commit
- QuestionQuiz: What counts as proof
- QuestionQuiz: A changed value in a test