Skip to main content

8 posts tagged with "React"

View all tags

FastAPI 422 or useParams Undefined? 4 Contract Mismatches

ยท 6 min read

Three classic scenes in frontend-backend integration: a POST returns 422; a route page's parameter stays undefined forever; an SSE request sits at 200 while the UI silently shows nothing. Different symptoms, one family of root causes โ€” the two sides disagreeing about the interface contract.

Encountered this while building an AI Agent SaaS platform for a client, frontend and backend developed in parallel โ€” we hit all four, and here is the locating method and the prevention discipline.

TL;DRโ€‹

Contract mismatches come in four shapes, producing three kinds of symptoms:

PitfallMismatchSymptom
Field namefrontend sends name, backend wants label422
Field typefrontend sends objects, backend expects List[str]422
Route paramroute defines :id, component reads agentIdundefined, feature silently dead
Event fieldbackend pushes {"content": ...}, frontend checks token200, UI shows nothing

Prevention is a single discipline: align on the schema before writing code โ€” field names, types, route param names, event data shapes, all sourced from the backend schema (or an interface doc both sides confirmed).

Pitfall 1: Field Name Mismatch โ†’ 422โ€‹

The most basic one. The frontend TypeScript interface declares name + key for creating an API key; the backend Pydantic schema expects label + api_key:

// what the frontend sends
interface CreateApiKeyInput {
name: string
key: string
}

# what the backend declares
class ApiKeyCreate(BaseModel):
label: str
api_key: str
POST /api/api-keys โ†’ 422 Unprocessable Entity

Locate it from the 422 response body โ€” don't guess. FastAPI's 422 carries a detail array spelling out every missing field and why:

[
{ "loc": ["body", "label"], "msg": "Field required", "type": "missing" },
{ "loc": ["body", "api_key"], "msg": "Field required", "type": "missing" }
]

Field required = the field is not in your request body at all = a field-name mismatch. Expand the response in the Network tab and it takes ten seconds.

Pitfall 2: Field Type Mismatch โ†’ 422โ€‹

Names can line up and types can still betray you. The backend declares mcp_tools as a list of strings; the frontend sends an array of objects (each with tool_id and token_id โ€” the business genuinely needs OAuth token binding):

// what the frontend sends
{ mcp_tools: [{ tool_id: "t1", token_id: "k1" }] }

# what the backend expects
mcp_tools: List[str]
PATCH /api/agents/{id} โ†’ 422 Unprocessable Entity

This time detail says Input should be a valid string โ€” a type mismatch. The fix is making the backend schema accept both shapes (the frontend's structure has a real business reason to exist; don't amputate it):

from typing import List, Union

class McpToolConfig(BaseModel):
tool_id: str
token_id: str | None = None

mcp_tools: List[Union[str, McpToolConfig]]

Union lets the schema accept both a plain string (tool reference only) and an object (with binding config); Pydantic tries them in order. The pattern generalizes to any "API evolves, frontend moves first" situation: the schema accommodates the real business shape, not the other way around.

Pitfall 3: useParams Name Mismatch โ†’ undefinedโ€‹

Route definition and component each written from memory, one word apart:

// route definition
<Route path="/agents/:id/memory" element={<MemoryPage />} />

// component
const { agentId } = useParams<{ agentId: string }>()
// agentId is undefined forever โ€” the route param is named id, not agentId

No error, status codes fine, feature silently dead โ€” agentId is undefined, so downstream API calls carry undefined or never fire.

Two fixes:

// 1. match the route definition
const { id } = useParams<{ id: string }>()

// 2. or rename while destructuring
const { id: agentId } = useParams<{ id: string }>()

What makes this one sneaky is the generic: useParams<{ agentId: string }> โ€” TypeScript does not verify that the keys in your generic actually exist in the route definition. The type annotation hands you false confidence.

Pitfall 4: Event Field Mismatch โ†’ 200 but Silent Failureโ€‹

In an SSE stream, the backend pushes {"content": "..."} while the frontend's event check looks for token:

// the frontend's event predicate
const isTokenEvent = (d: any) => 'token' in d // always false

// what the backend actually pushes
data: {"content": "hello"}

The Network tab shows 200 and the stream flowing; the UI shows nothing โ€” the predicate never fires and events are silently dropped. This one is harder to catch than a 422: no error, just a feature that never happens.

Fix: align the predicate with the backend's actual data shape:

const isTokenEvent = (d: any) => 'content' in d && !('type' in d)

For SSE/WebSocket interfaces carrying many event kinds over one connection, prefer an explicit type field for dispatching; inferring event kinds from "which keys happen to exist" turns every contract change into silent breakage.

Prevention: One Disciplineโ€‹

All four pitfalls share an origin: each side wrote its half of the interface from imagination. Prevention needs no tooling, one discipline โ€”

Before writing any interface code, align on the schema: field names, types, route param names, event shapes โ€” item by item. The backend Pydantic schema (or OpenAPI doc) is the single source of truth; the frontend TypeScript interfaces mirror it. Whoever changes the contract changes the schema first, both sides confirm, then code moves.

When symptoms appear, triage in order: 422 โ†’ expand the response detail and read loc; undefined โ†’ check the route's :param names; 200 but nothing happened โ†’ capture a real response and diff it field-by-field against the frontend predicate.

The server side of streaming interfaces has a companion pitfall (exceptions and leaked resources on client disconnect), covered in FastAPI SSE CancelledError on Client Disconnect? Catch and Re-raise in the Generator.

Watch out

Frontend TypeScript interfaces (interface XxxInput) are compile-time paper constraints โ€” as any and third-party request wrappers can bypass them entirely. Types matching does not mean fields matching. The final arbiter of contract truth is always a comparison against the backend schema, not the absence of red squiggles.

FAQโ€‹

Why does FastAPI return 422 Unprocessable Entity?โ€‹

In 9 out of 10 cases the request body does not match the Pydantic schema: a field name the backend does not expect (sending name when the schema wants label) or a field type mismatch (an array of objects where List[str] is declared). The 422 response body lists every offending field in its detail array โ€” read it before guessing.

How do I debug which field caused a FastAPI 422?โ€‹

Open the response body in the browser Network tab or curl: FastAPI returns a detail array where each entry has loc (the field path), msg (Field required / Input should be a valid string), and type. loc pointing at a field you did send under a different name is the classic field-name mismatch.

Why does useParams return undefined in React Router?โ€‹

The keys of useParams come from the route definition: a route of /agents/:id exposes only id. Destructuring a name that does not appear in any :param โ€” like agentId โ€” yields undefined silently, no error thrown. Rename during destructuring instead: const { id: agentId } = useParams().

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

vaul Drawer Won't Close or Scroll? Overflow Blocks the Drag

ยท 6 min read

On a real phone, our filter drawer would open but neither scroll nor dismiss โ€” while the exact same drawer worked flawlessly in desktop browsers.

I hit this while building Life, an AI bookkeeping assistant โ€” filters and category management both live in bottom drawers. And we fixed this bug twice: after the first fix, a page rewrite rebuilt the drawer JSX from memory, and the same bug was back within hours.

TL;DRโ€‹

  • Root cause: the DrawerContent root element is vaul's drag layer (it owns the pull-to-dismiss gesture). With overflow-y-auto on the root (plus max-h-[80vh]-style height caps), the browser judges the touch gesture as "scroll this container" and vaul's drag listeners never receive it โ€” the drawer neither scrolls (content clipped by max-h) nor dismisses.
  • Fix: sink scrolling into an inner layer โ€” the root keeps only fixed regions (the header), and content goes into a flex-1 min-h-0 overflow-y-auto wrapper.
  • Meta-lesson: re-fixing a structural bug means starting from the template/rule, not from memory of the old JSX.

The symptom: fine on desktop, frozen on real devicesโ€‹

The drawer is shadcn/ui's Drawer (vaul ^1.1.2 underneath). The failure pattern: on desktop, scroll and dismiss both work; on real devices the content area won't scroll and pulling down won't close โ€” the drawer feels frozen. And "can't scroll" always came together with "can't close".

That pairing points at a gesture problem, not a styling problem: on mobile, scrolling and dragging are the same finger doing the same touch move. Whether the browser or the component gets the gesture depends on which element it lands on.

Root cause: the scroll container and the drag layer fight over one gestureโ€‹

vaul's pull-to-dismiss relies on touch gesture listeners on the root element: press anywhere, drag down, the root keeps receiving touchmove, and past a threshold the drawer closes.

When the root is also a scroll container, the mobile browser's gesture arbitration steps in first: the finger movement is interpreted as "scroll this container", the browser consumes the touch events, and vaul's listeners never see enough touchmove for a dismiss decision. That's exactly why "can't scroll" and "can't close" appear as a pair โ€” the scroll container wins the gesture, vaul loses it, and the content stays clipped by max-h anyway.

The broken structure (from the real diff, after the regression):

{/* Wrong: the root is the drag layer, yet carries scroll + height cap */}
<DrawerContent className="max-h-[80vh] overflow-y-auto px-4 pb-6 text-left">
<DrawerHeader>
<DrawerTitle>Filters</DrawerTitle>
</DrawerHeader>
<div className="flex flex-col gap-4">{/* content */}</div>
<DrawerFooter>{/* actions */}</DrawerFooter>
</DrawerContent>

This renders perfectly in desktop browsers โ€” the mouse wheel drives the scroll container directly, and vaul's handle still dismisses. Which is exactly why it slips through development and only surfaces in real-device testing.

The fix: sink scrolling to an inner layer, keep the root fixedโ€‹

The correct structure strips scrolling off the root and hands it to an inner container; the header stays on the root:

{/* Right: no overflow on the root, scrolling sinks inward */}
<DrawerContent className="text-left">
<DrawerHeader>
<DrawerTitle>Filters</DrawerTitle>
</DrawerHeader>
<div className="flex-1 min-h-0 overflow-y-auto px-4 pb-6">
{/* content + footer scroll here */}
</div>
</DrawerContent>

Three details that matter:

  1. Zero overflow, zero max-h on the root โ€” the drag gesture stays live, so pulling down anywhere dismisses.
  2. flex-1 min-h-0 on the inner layer โ€” a flex child defaults to min-height: auto; without pinning it to zero, the content stretches the drawer and the inner layer never produces a scrollbar. min-h-0 is the silent precondition for scrolling to work at all.
  3. The header stays on the root โ€” visually the title is fixed while content scrolls; interactively, dragging the handle or title means "close" while swiping the content means "scroll". Each gesture goes to its owner.

After the fix, three Playwright assertions verified it: root overflowY === 'visible', inner scrollTop scrolls independently, and a simulated drag-down dismisses the drawer. All three passed, with no desktop regression.

Why it regressed: rebuilding JSX from memoryโ€‹

The regression itself is the more instructive part. The first fix (commit a182098, 2026-09-23 08:55) solved "can't scroll on mobile". Later, a page rewrite rebuilt the drawer JSX without consulting the fix โ€” whoever wrote it worked from memory of the old code, and max-h + overflow-y-auto went right back on the root. The second fix (f1097b2) landed at 12:10 the same day, under 4 hours after the first.

Structural bugs โ€” DOM hierarchy, gesture ownership, scroll container placement โ€” are different from ordinary logic bugs: remembering the conclusion isn't enough, because the person rewriting the code isn't necessarily the person who hit the bug, and the memory isn't necessarily theirs either. What works: distill the correct structure into a copyable template with a one-line rule โ€” "the DrawerContent root is vaul's drag layer; no overflow or max-h on it; sink scrolling inward" โ€” copy the template on every rewrite, and run the gesture assertions once.

Watch out

"Sink scrolling inward" isn't vaul-specific: any component whose root carries drag gestures โ€” bottom sheets, draggable dialogs โ€” follows the same rule: the gesture layer and the scroll layer must be separate elements. Also remember min-h-0 in flex column layouts: without it the symptom is "no scrollbar appears and the drawer stretches", which is different from the root-overflow symptom. When debugging, first confirm the scroll container itself can scroll, then trace gesture ownership upward.

FAQโ€‹

Why doesn't my vaul drawer scroll on mobile?โ€‹

Check whether the DrawerContent root carries overflow-y-auto or a max-h cap. The root element is vaul's drag layer โ€” a scroll container on it makes the browser judge touch movement as scrolling, so vaul's drag listeners never fire. Sink scrolling into an inner flex-1 min-h-0 overflow-y-auto container and keep the header fixed on the root.

Why can't I close my vaul drawer by dragging down?โ€‹

Same root cause as the scrolling failure: with the scroll container on the root, the browser consumes the touch gesture as scroll and vaul's dismiss gesture never triggers. Once scrolling moves to an inner layer, both symptoms disappear together โ€” swiping the content scrolls, dragging the handle or title closes.

Where does the scroll container go in a vaul drawer?โ€‹

Inside. The DrawerContent root keeps zero overflow and zero max-h so the drag gesture stays live; content goes into an inner flex-1 min-h-0 overflow-y-auto wrapper. min-h-0 matters: a flex child defaults to min-height auto, and without it the content stretches the drawer instead of producing a scrollbar.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

Clicking One Row Highlights Many in Ant Design Table? Your rowKey Isn't Unique

ยท 5 min read

Clicking a table row on a reporting page to inspect details, the clicked row โ€” plus several other rows โ€” highlighted at the same time, while the console flooded with React duplicate key warnings.

Encountered this while building AI Ops โ€” LLM-powered analysis that surfaces market trends, user behavior, and sales insights to drive precise operations strategy. The ad weekly-report page contains several detail tables (campaign ร— keyword, campaign ร— area), each supporting click-to-highlight so users can drill into a row's delivery details. After launch, clicking any row "lit up" every row under the same campaign.

TL;DRโ€‹

Ant Design's Table uses the return value of rowKey as each row's React key. When that field isn't the data's real business key โ€” guessed by naming, or missing a dimension that participates in uniqueness โ€” multiple rows generate identical keys: every key-matched row interaction (selection, highlight, expansion) hits multiple rows at once, and React throws duplicate key warnings. The fix: query information_schema for the table's actual columns, pick a truly unique column or composite columns for rowKey, and verify with GROUP BY HAVING.

The Symptomโ€‹

A minimal reproduction (Ant Design 5 + React 18):

import { Table } from 'antd';
import { useState } from 'react';

// Data granularity: keyword ร— product โ€” one keyword splits into multiple rows per promoted product
const data = [
{ keyword_id: 88, keyword: 'summer dress', offer_id: 101, clicks: 12 },
{ keyword_id: 88, keyword: 'summer dress', offer_id: 102, clicks: 7 },
{ keyword_id: 90, keyword: 'maxi skirt', offer_id: 103, clicks: 5 },
];

export default function WeeklyKeywords() {
const [selected, setSelected] = useState<string[]>([]);
return (
<Table
rowKey={(r) => String(r.keyword_id)} // Pitfall: keyword_id is not unique at this granularity
columns={[
{ title: 'Keyword', dataIndex: 'keyword' },
{ title: 'Product', dataIndex: 'offer_id' },
{ title: 'Clicks', dataIndex: 'clicks' },
]}
dataSource={data}
rowSelection={{ selectedRowKeys: selected, onChange: setSelected }}
onRow={(r) => ({ onClick: () => setSelected([String(r.keyword_id)]) })}
/>
);
}

Two symptoms: clicking the first row highlights both rows with keyword_id 88, and the console repeatedly prints:

Warning: Encountered two children with the same key, `88`.
Keys should be unique so that components maintain their identity across updates.

Root Causeโ€‹

An antd Table row's identity is exactly the return value of rowKey. It becomes the React key of that row's element. When keys duplicate, React's diff treats multiple rows as the same element: rendering can go wrong and controlled state bleeds between rows.

Every key-matched row interaction gets amplified. rowSelection's selectedRowKeys, onRow clicks, and expandedRowKeys all match by key โ€” with duplicate keys, one match hits multiple rows. That's the direct cause of "click one, highlight many."

The wrong key column usually comes from the data side. The actual root cause here: key columns were guessed from naming โ€” we assumed the area table had region_id, but its real business key column was area_name; we assumed the keyword table's granularity was keyword, but it was actually keyword ร— product (offer_id also participates in the unique key). Miss one dimension and every row in a group shares the same rowKey.

The Fixโ€‹

Step 1: Query the table's actual columns โ€” don't guess from namesโ€‹

SELECT column_name, data_type
FROM information_schema.columns
WHERE table_name = 'ad_weekly_keywords'
ORDER BY ordinal_position;

Confirm which columns actually form the business key, and whether the column you assumed even exists.

Step 2: Verify the key (or key combination) is uniqueโ€‹

SELECT keyword, offer_id, COUNT(*)
FROM ad_weekly_keywords
GROUP BY keyword, offer_id
HAVING COUNT(*) > 1;
-- 0 rows = unique; also confirm key columns contain no NULLs

Step 3: Configure rowKey with a composite keyโ€‹

<Table
rowKey={(r) => `${r.keyword}::${r.offer_id}`}
// Or even safer: JSON.stringify([r.keyword, r.offer_id])
dataSource={data}
...
/>

When concatenating composite keys, use a separator that cannot appear in the field values (or just JSON.stringify the array) to avoid collisions between a + b and ab.

After the change, clicking a row highlights only that row, and duplicate key warnings drop to zero. This is the same family of problems as React list key duplicates causing DOM errors โ€” only with unique keys can diffing and row interactions be correct.

Heads up

Before choosing key columns, query information_schema for the table's actual columns โ€” don't guess from field names: business key columns can differ entirely from intuition (the table has only area_name, no region_id; keyword granularity is actually keyword ร— product).

The duplicate key warning is not "just a warning": it means React reconciliation is broken โ€” row state bleeding, wrong highlights, and updates not taking effect can all follow. It must go to zero.

After changing rowKey, re-verify uniqueness with GROUP BY ... HAVING COUNT(*) > 1, and check key columns for NULLs โ€” NULL keys create duplicates too.

FAQโ€‹

How should I set rowKey on an Ant Design Table?โ€‹

Use the field โ€” or combination of fields โ€” that uniquely identifies a row: a single unique field works directly; if no single field is unique, build a composite key from multiple columns (with a collision-proof separator or JSON.stringify). Never use a non-unique business field, and don't take shortcuts with array index โ€” after sorting, filtering, or pagination, state will bleed between rows.

How do I fix the React duplicate key warning?โ€‹

Duplicate keys make React treat multiple nodes as the same element, corrupting rendering and state. Locate the list rendering site producing the duplicate keys, switch to a truly unique key, then verify uniqueness at the data source with GROUP BY HAVING โ€” silencing the warning without checking the data means the problem will resurface in another form.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

Bypass Supabase Auth for Playwright E2E Testing Without Login

ยท 4 min read

Encountered this issue while building an AI Agent SaaS platform for a client. Here's the root cause and solution.

TL;DRโ€‹

E2E tests shouldn't depend on real OAuth login flows. By detecting localStorage test markers in the useAuth hook, you can inject mock auth state directly and skip Supabase initialization. Also change the Zustand store's loading default to false to prevent AuthGuard from showing an infinite spinner.

Fix React List Key Duplication Causing DOM Errors

ยท 2 min read

Encountered this issue while building an AI Agent chat interface. Here's the root cause and solution.

TL;DRโ€‹

Date.now() millisecond timestamps can duplicate within the same millisecond. When used as React list keys, this causes DOM errors. Fix by adding a random suffix or using crypto.randomUUID().