Vibe coding with Claude Code course · Module 5: Reddit clone

The guild register: communities and a filter in the address

9 min read ·
In this lesson10

Crew Council is growing and treasure maps, hull-patching tips and battle tales are all mixed in one list. Whoever wants only maps digs through the whole river of posts. Reddit divides content into communities, that is subreddits, and we will call them guilds: each has a topic, a description, rules and its members. In this lesson Claude Code first plans the split, and you check in the plan and in the browser that a guild is a filter, not a second book.

The problem: one book, many windows

The most important decision is made before the code. A guild has no list of posts of its own. Every post has a community field with the guild's id, and the guild view is the same list seen through a filter. If guilds had separate copies, a new post would land in one of them, and a vote cast in one copy would not exist in the other.

The second decision: where to keep the selected guild. It could live in useState, but then it disappears on refresh and you cannot send a link to a guild to a shipmate. So it goes into the address as a search parameter, which you know from lesson 3_5: /?community=sea-battles. The link can be sent, a refresh remembers the choice, and the Back button returns to the previous guild.

Request for Claude Code: a plan first

The change touches several files and leaves choices, so you start with plan mode from lesson 0_4:

Request for Claude Code:

/plan Split the Crew Council posts into communities. In lib/communities.ts
a Community type (id, name, displayName, description, members, rules)
and four guilds: treasure-hunting, sea-battles, pirate-life,
ship-building. The selected guild lives in the address as ?community=,
and @app/page.tsx reads it from searchParams; an unknown id gives a 404.
A sidebar with links: All and four guilds with the number of members
in short form (12.5K). Above the posts a guild header with the
description, rules and a Join button. A new-post form with a guild
choice, a title up to 300 characters and a body. Do not keep the
filtered list in a separate state, compute it from the posts. End
every step with tests, lint and build.

In the plan you look for three things. Whether the filtered list is computed, not kept in a second useState. Whether the posts state stays in Feed from lesson 4_1 and does not move to a new component. Whether there are no new packages. A plan that passes you accept with Yes, manually approve edits and you read every edit.

What Claude wrote: guild data

Open lib/communities.ts. The Community type describes one guild:

export interface Community {
  id: string;
  name: string;
  displayName: string;
  description: string;
  members: number;
  rules: string[];
}

Each field has its reader. id, for example treasure-hunting, is read by the program: it stands in the address and in the post's community field. name is the name with a prefix, r/TreasureHunting, and displayName is the readable header title. members is the number of members, and rules is an array of the guild's rules. The number of members is shown in short form by a function from the same file:

export function formatMembers(count: number): string {
  if (count >= 1000000) return (count / 1000000).toFixed(1) + "M";
  if (count >= 1000) return (count / 1000).toFixed(1) + "K";
  return String(count);
}

From a thousand it divides by 1000, toFixed(1) keeps one digit after the dot and appends K, so the 12460 members of r/TreasureHunting become 12.5K, and the 25670 members of r/PirateLife become 25.7K. From a million it works the same way with the letter M. Small numbers come back unchanged.

What Claude wrote: the address as the source of truth

Open app/page.tsx. The page reads the guild from the address the way the search box did in lesson 3_5:

export default async function Home({ searchParams }: PageProps<"/">) {
  const { community } = await searchParams;
  const id = typeof community === "string" ? community : null;
  const selected = communities.find((c) => c.id === id) ?? null;
  if (id && !selected) {
    notFound();
  }

typeof community === "string" rejects a missing parameter and a list from an address like ?community=a&community=b. find returns the first guild with a matching id or undefined, which ?? null turns into null, meaning "all guilds". An address with an unknown id, for example /?community=kraken, ends in a 404 page instead of an empty list that would pretend the guild exists. Below, the page assembles the sidebar and Feed, and passes the selected guild to both.

components/CommunitySidebar.tsx has no state, so it stays a Server Component. Each guild is a link:

<Link
  key={community.id}
  href={{ pathname: "/", query: { community: community.id } }}
  aria-current={selectedCommunity === community.id ? "page" : undefined}
  className={selectedCommunity === community.id ? active : idle}
>

href as an object builds the address itself and encodes special characters, so you do not glue text by hand. aria-current="page" tells a screen reader which guild is open, and active and idle are two sets of classes from the top of the file: the selected guild has a grey background and bold text. The first link, All, simply leads to /. A link from next/link moves between guilds without reloading the page, as in lesson 2_1.

The filter in Feed

Open components/Feed.tsx. A community prop arrived with the selected guild or null, and the list to show is computed from the posts:

const selectedCommunity = community?.id ?? null;
const filtered = selectedCommunity
  ? posts.filter((post) => post.community === selectedCommunity)
  : posts;
const visiblePosts = sortPosts(filtered, sortMode);

filter keeps the posts whose community matches the selected guild. When no guild is selected, selectedCommunity is null and all posts pass. The sorting from lesson 4_1 works on the filtered list. The posts state has not changed at all: moving to another guild changes only the address, and Feed stays in its place on the page, so votes and new posts survive a walk between guilds.

The header and the Join button

Above the posts stands CommunityHeader with a banner, the first letter of the name in a circle as an icon, a description, the number of members and the rules. The Join button changes its label to Joined. Where to keep that information? If the header had its own useState, React would keep that state when moving from one guild to another, because it is the same component in the same place, and r/SeaBattles would show "Joined" after a click in r/TreasureHunting. That is why the list of guilds you joined is held by Feed:

const [joined, setJoined] = useState<string[]>([]);

const toggleJoin = (id: string) => {
  setJoined((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));
};

includes checks whether the id is already on the list. If it is, filter builds the list without it; if not, the spread appends it at the end. The header gets isJoined={joined.includes(community.id)} and an onToggleJoin function, and remembers nothing itself.

The new-post form

components/CreatePostForm.tsx is the controlled form from lesson 2_3 with guild, title and body fields. The submit button guards two conditions:

<button
  type="submit"
  disabled={!community || !title.trim()}
  className="rounded-full bg-orange-600 px-4 py-1 font-semibold text-white disabled:bg-gray-300"
>
  Publish
</button>

With no guild selected or an empty title the button is disabled. The title field has maxLength={300}, so the browser will not accept longer text. A submitted form calls addPost in Feed, which adds the post at the start of the list with one upvote from the author, userVote: "up". The form starts from the guild in the address, and in Feed it has key={selectedCommunity ?? "all"}: a new key after a guild change tells React to start the form over, with the new guild in the select.

Captain's review

  1. A second list in state. This is the typical agent mistake: filteredPosts in a separate useState, refilled after a guild click. A new post lands in posts but not in filteredPosts, so it vanishes from view until the next click. When the agent syncs the copy with an effect, npm run lint stops it with the rule react-hooks/set-state-in-effect:
error  Error: Calling setState synchronously within an effect can trigger cascading renders
  > 11 |     setFilteredPosts(
       |     ^^^^^^^^^^^^^^^^ Avoid calling setState() directly within an effect

The cure is not to silence the rule but to remove the copy: the list to show is the result of filter on every render.

  1. An unknown guild. Type /?community=kraken. You want a 404 page, not a white screen with an error. An agent likes to write communities.find(...)!; the exclamation mark makes TypeScript believe the guild will be found, and with a wrong address the page crashes reading a field of undefined.

  2. A walk between guilds. Vote for a post, enter its guild, add a post there and go back to All. The vote and the new post should stay. Join r/TreasureHunting and go to r/SeaBattles: there the button should say Join.

  3. A check in the browser. You can hand this walk to Claude in Chrome from lesson 3_8: "Open localhost:3000, go to r/TreasureHunting, add a post, click All, go back with the Back button and tell me what you see in the list and in the console". This is the same loop as with tests: an exam that gives an answer instead of the agent's assurance.

Next step

When the review passes, ask for a commit, for example "Communities: filter in the address, header and post form". Then a test for formatMembers, because it is a pure function with numbers in and text out:

Write tests of formatMembers in lib/communities.test.ts: 950 gives "950",
12460 gives "12.5K", 999950 gives "1.0M". Run them before any change
in the code and show the result.

The last case will not pass: Vitest will report expected '1000.0K' to be '1.0M', because 999,950 is not yet a million, and after rounding the thousands you get 1000.0. Tell Claude to fix the function, not the test, and read the fix in the diff. Before the next lesson type /clear: a new feature is a new conversation, and the old one stays available to resume. In the editor below waits the guild register; there is no address there, so useState holds the choice, while in the project the address holds it. Join a guild, add a post and switch the filter.

Remember: a guild is the same register of posts seen through another window, and the page address says which window is open.

Code for this lesson: App.jsx
// Guild register: a community is a filter on the same list of posts.
// The editor has no address bar, so useState holds the choice;
// in the Crew Council project the address (?community=) holds it.
import { useState } from 'react';

const communities = [
  { id: 'treasure-hunting', name: 'r/TreasureHunting', displayName: 'Treasure Hunting', description: 'Maps, discoveries and treasure from every sea.', members: 12460, rules: ['Share real finds', 'Do not reveal the locations of ongoing expeditions'] },
  { id: 'sea-battles', name: 'r/SeaBattles', displayName: 'Sea Battles', description: 'Naval battles, strategies and tactics.', members: 8920, rules: ['Describe battles in detail', 'Respect your opponent'] },
  { id: 'pirate-life', name: 'r/PirateLife', displayName: 'Pirate Life', description: 'Everyday life on deck.', members: 25670, rules: ['Be yourself', 'Respect the pirate code'] },
  { id: 'ship-building', name: 'r/ShipBuilding', displayName: 'Ship Building', description: 'Building and repairing ships.', members: 5430, rules: ['Show plans and sketches', 'Help beginners'] },
];

const startPosts = [
  { id: 'p1', community: 'pirate-life', title: 'Sail to Tortuga or head north?' },
  { id: 'p2', community: 'treasure-hunting', title: 'Treasure map with an X on Skull Island' },
  { id: 'p3', community: 'ship-building', title: 'How do you patch a hull with tar?' },
  { id: 'p4', community: 'sea-battles', title: 'The Kraken sank our longboat' },
];

function formatMembers(count) {
  if (count >= 1000000) return (count / 1000000).toFixed(1) + 'M';
  if (count >= 1000) return (count / 1000).toFixed(1) + 'K';
  return String(count);
}

function CommunityHeader({ community, isJoined, onToggleJoin }) {
  return (
    <header className="overflow-hidden rounded-lg border border-gray-200 bg-white">
      <div className="h-12 bg-linear-to-r from-red-900 to-gray-900" />
      <div className="flex items-start gap-3 p-3">
        <span aria-hidden="true" className="-mt-8 flex h-12 w-12 items-center justify-center rounded-full border-4 border-white bg-red-800 text-xl font-bold text-white">
          {community.displayName[0]}
        </span>
        <div className="flex-1">
          <h2 className="font-bold">{community.displayName}</h2>
          <p className="text-xs text-gray-500">{community.name} · {formatMembers(community.members)} members</p>
          <p className="text-sm">{community.description}</p>
        </div>
        <button
          type="button"
          onClick={onToggleJoin}
          aria-pressed={isJoined}
          className={isJoined ? 'rounded-full border px-3 py-1 text-sm' : 'rounded-full bg-blue-600 px-3 py-1 text-sm text-white'}
        >
          {isJoined ? 'Joined' : 'Join'}
        </button>
      </div>
      <ol className="list-inside list-decimal border-t border-gray-200 px-3 py-2 text-sm">
        {community.rules.map((rule) => (
          <li key={rule}>{rule}</li>
        ))}
      </ol>
    </header>
  );
}

function CreatePostForm({ defaultCommunity, onSubmit }) {
  const [community, setCommunity] = useState(defaultCommunity ?? '');
  const [title, setTitle] = useState('');
  const handleSubmit = (event) => {
    event.preventDefault();
    if (!community || !title.trim()) return;
    onSubmit({ community, title: title.trim() });
    setTitle('');
  };
  return (
    <form onSubmit={handleSubmit} className="space-y-2 rounded-lg border border-gray-200 bg-white p-3">
      <select value={community} onChange={(event) => setCommunity(event.target.value)} aria-label="Community" className="w-full rounded border border-gray-300 p-2">
        <option value="">Choose a community</option>
        {communities.map((c) => (
          <option key={c.id} value={c.id}>{c.name}</option>
        ))}
      </select>
      <input value={title} onChange={(event) => setTitle(event.target.value)} maxLength={300} placeholder="Title" aria-label="Post title" className="w-full rounded border border-gray-300 p-2" />
      <button type="submit" disabled={!community || !title.trim()} className="rounded-full bg-orange-600 px-4 py-1 font-semibold text-white disabled:bg-gray-300">
        Publish
      </button>
    </form>
  );
}

export default function App() {
  const [posts, setPosts] = useState(startPosts);
  const [selectedCommunity, setSelectedCommunity] = useState(null);
  const [joined, setJoined] = useState([]);

  // The list to show: computed on every render, with no second state
  const filtered = selectedCommunity ? posts.filter((post) => post.community === selectedCommunity) : posts;
  const community = communities.find((c) => c.id === selectedCommunity) ?? null;

  const toggleJoin = (id) => {
    setJoined((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));
  };

  const addPost = (draft) => {
    setPosts((prev) => [{ ...draft, id: String(Date.now()) }, ...prev]);
  };

  const linkClass = (active) => (active ? 'block w-full rounded px-3 py-2 text-left bg-gray-200 font-semibold' : 'block w-full rounded px-3 py-2 text-left hover:bg-gray-200');

  return (
    <div className="min-h-screen bg-gray-100 p-4 text-gray-900">
      <div className="mx-auto flex max-w-3xl flex-col gap-4 md:flex-row">
        <nav aria-label="Communities" className="space-y-1 md:w-48 md:shrink-0">
          <button type="button" onClick={() => setSelectedCommunity(null)} aria-current={selectedCommunity === null ? 'page' : undefined} className={linkClass(selectedCommunity === null)}>
            All
          </button>
          {communities.map((c) => (
            <button key={c.id} type="button" onClick={() => setSelectedCommunity(c.id)} aria-current={selectedCommunity === c.id ? 'page' : undefined} className={linkClass(selectedCommunity === c.id)}>
              <span className="block text-sm">{c.name}</span>
              <span className="block text-xs text-gray-500">{formatMembers(c.members)} members</span>
            </button>
          ))}
        </nav>
        <main className="flex-1 space-y-3">
          {community && (
            <CommunityHeader community={community} isJoined={joined.includes(community.id)} onToggleJoin={() => toggleJoin(community.id)} />
          )}
          <CreatePostForm key={selectedCommunity ?? 'all'} defaultCommunity={selectedCommunity} onSubmit={addPost} />
          {filtered.length === 0 && <p className="text-gray-500">This guild has no posts yet.</p>}
          {filtered.map((post) => (
            <article key={post.id} className="rounded-lg border border-gray-200 bg-white p-3">
              <p className="text-xs text-gray-500">{communities.find((c) => c.id === post.community)?.name}</p>
              <h3 className="font-semibold">{post.title}</h3>
            </article>
          ))}
        </main>
      </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. What is a community (subreddit)?

  2. 2. How do you filter posts belonging to the selected community?

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

Hands-on tasks in the game

  • Click in order

    Build the post filter by community by clicking the tokens in order:

  • Code editor

    Communities sidebar

  • Horizontal ordering

    Arrange the condition comparing a post's community to the selected one (one line, left to right):

  • Code editor

    Community header

  • Vertical ordering

    Order what happens after you click Publish in the form in r/TreasureHunting:

  • Horizontal ordering

    Arrange the attribute that disables the Publish button without a guild or without a title (one line, left to right):

  • Code editor

    Create post in community

  • Vertical ordering

    Order the communities from the most to the fewest members (PirateLife 25670, TreasureHunting 12460, SeaBattles 8920, ShipBuilding 5430):

  • Click in order

    Build the expression formatting millions of members by clicking the tokens in order:

  • Horizontal ordering

    Arrange the community name notation (one line, left to right):

  • Vertical ordering

    Order what the home page from the lesson does after you visit the address /?community=kraken:

  • Click in order

    Build the lookup of the guild with the id read from the address by clicking the tokens in order:

  • Horizontal ordering

    Arrange the character-limit attribute of the title input (one line, left to right):

  1. QuestionQuiz: Communities
  2. QuestionQuiz: Filtering by community
  3. Click in orderSequence: Community filter
  4. Coding taskPractice: Community list
  5. Put in orderSorting: Community comparison
  6. QuestionQuiz: formatMembers
  7. Coding taskPractice: Community header
  8. Put in orderSorting: The path of a new post
  9. QuestionQuiz: Where the Join state lives
  10. Put in orderSorting: Blocking the Publish button
  11. QuestionQuiz: Post form validation
  12. Coding taskPractice: Create post form
  13. Put in orderSorting: Communities by member count
  14. QuestionQuiz: All Communities
  15. Click in orderSequence: formatMembers million
  16. Put in orderSorting: Community name
  17. Put in orderSorting: An unknown guild in the address
  18. QuestionQuiz: Community rules
  19. Click in orderSequence: Find the selected community
  20. Put in orderSorting: Title character limit

Useful articles