Resilient Chargeback Inbox: Normalize, Cache, and Cancel in React
Data Structure DesignModel answerLast updated
Build a React dispute list that normalizes inconsistent API data, caches queries for 60 seconds, and avoids stale responses when filters or search change quickly.
Problem
You are building a React component that lists payment disputes from an internal endpoint, GET /api/v1/disputes. The endpoint has no documentation and its response shape is still changing. The component must treat the payload as untrusted, convert it into a strict client-side model, avoid duplicate network calls, and stay correct when the user changes inputs quickly.
Implement DisputeInbox({ fetchDisputes, pageSize = 10 }). Assume fetchDisputes(query, signal) resolves with the raw JSON body, where query is { status, search, page, pageSize }.
Normalization rules
The body has the form { "data": [...], "has_more": boolean }. Items are inconsistent:
- Identifier: a string under
idordispute_id. - Amount: integer cents (
amount: 2500), a float in dollars (amount_dollars: 25.0), or a currency string ("$25.00"). Output is always integer cents. - Status: map the raw string to
'needs_response','under_review', or'closed'. Any unrecognized value becomes'needs_response'. - Created time: Unix seconds (
created) or an ISO 8601 string (created_at). Output is Unix epoch milliseconds. - Reason: an optional string, used for search.
// Raw
{
"data": [
{ "dispute_id": "dp_101", "amount": 4200, "status": "warning_needs_response", "created": 1700000000 },
{ "id": "dp_102", "amount_dollars": 15.5, "status": "WON", "created_at": "2023-11-14T22:13:20Z" }
],
"has_more": false
}
// Normalized
[
{ id: "dp_101", amountCents: 4200, status: "needs_response", createdAtMs: 1700000000000 },
{ id: "dp_102", amountCents: 1550, status: "closed", createdAtMs: 1700000000000 }
]
Component requirements
- Filter by
'all' | 'needs_response' | 'under_review' | 'closed'. - Search by dispute identifier or reason.
- Keep an in-memory cache keyed by
status,search, andpage, with a 60-second TTL. - If the query changes while a request is in flight, that request must not overwrite newer state.
- Show
Loading...while fetching, aRetrybutton on failure, andNo disputes foundfor an empty result.
Constraints
- Never mutate the raw response.
- Convert dollar floats with rounding, not truncation, to avoid floating-point drift.
- Clicking
Retrymust not clear the filter or search inputs. - Cache keys must not depend on the order in which parameters are listed.
What to deliver
Explain your design, then give the code for the normalizer, the cache key and TTL logic, and the component. Discuss edge cases and trade-offs.
Hints
Hint 1
Keep three concerns separate: a pure function that turns `unknown` into a strict model, a small cache keyed by a canonical string, and a single effect that does the fetching.
Hint 2
Give every effect run its own `AbortController` and abort it in the cleanup. Also check `signal.aborted` before calling `setState`, because a fetcher may ignore the signal.
Hint 3
Build the cache key from sorted parameter names and a trimmed, lowercased search string. Do not cache errors, and use `typeof` checks rather than truthiness so an amount of `0` stays valid.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The rendering is simple. The real work is keeping untrusted data at the edge, making the cache deterministic, and making stale writes impossible. I split the solution into three layers.
- Adapter. A pure function maps
unknownto a strictDisputeor rejects the item. React code never sees raw shapes. - Cache. A
Mapkeyed by a canonical string, storing{ value, storedAt }. Entries older than 60 s are treated as misses and deleted. - Fetch effect. It checks the cache first. On a miss it fetches with an
AbortController, and the cleanup aborts that request when any dependency changes.
I assume the server may not understand our normalized status names. So status and search filtering is applied client-side after normalization, which makes the UI correct regardless of backend behavior.
Normalization details
- Amount. An integer
amountis already cents. A number inamount_dollarsgoes throughMath.round(d * 100), which fixes cases like19.99 * 100 = 1998.9999.... A string has$, commas, and whitespace removed, then goes throughNumber.NaNrejects the item. - Status. Lowercase the string and match by substring:
needs_response,under_review, andwon/lost/closedmap to the three states. Everything else becomesneeds_response. That is also the safest default, since it errs toward "you may need to act." - Timestamp.
createdis seconds, so multiply by 1000.created_atgoes throughDate.parse, andNaNrejects the item. - Immutability. Each item is built as a fresh object.
- Bad envelope. If
datais not an array, throw. The user sees the error state instead of a misleading "No disputes found."
Concurrency
When filter, search, page, or a retry counter changes, React runs the previous effect's cleanup before the next effect. The cleanup aborts the old controller, and the signal.aborted guard stops a late resolution from touching state. Search is debounced (about 250 ms) to cut request volume, but correctness comes from abort plus the guard, not from the debounce. Changing the filter or search resets the page to 1.
Cache key
Sort the parameter names and serialize [name, value] pairs, so {page, status} and {status, page} give the same key. Trim and lowercase the search before it enters the key. Errors are never cached, so Retry always triggers a real request.
Code
import { useEffect, useRef, useState } from 'react';
type Status = 'needs_response' | 'under_review' | 'closed';
type Filter = 'all' | Status;
interface Dispute { id: string; amountCents: number; status: Status; createdAtMs: number; reason: string }
interface Query { status: Filter; search: string; page: number; pageSize: number }
interface Page { items: Dispute[]; hasMore: boolean }
interface Props {
fetchDisputes: (q: Query, signal: AbortSignal) => Promise<unknown>;
pageSize?: number;
}
const TTL_MS = 60_000;
const isObj = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null;
const toCents = (d: number) => (Number.isFinite(d) ? Math.round(d * 100) : null);
function parseAmount(r: Record<string, unknown>): number | null {
const { amount, amount_dollars: dollars } = r;
if (typeof amount === 'number') return Number.isInteger(amount) ? amount : toCents(amount);
if (typeof dollars === 'number') return toCents(dollars);
const s = typeof amount === 'string' ? amount : typeof dollars === 'string' ? dollars : null;
if (s === null) return null;
const cleaned = s.replace(/[$,\s]/g, '');
return cleaned === '' ? null : toCents(Number(cleaned));
}
export function normalizeStatus(raw: unknown): Status {
const s = typeof raw === 'string' ? raw.toLowerCase() : '';
if (s.includes('needs_response')) return 'needs_response';
if (s.includes('under_review')) return 'under_review';
if (['won', 'lost', 'closed'].some((k) => s.includes(k))) return 'closed';
return 'needs_response';
}
function parseCreated(r: Record<string, unknown>): number | null {
if (typeof r.created === 'number' && Number.isFinite(r.created)) return Math.round(r.created * 1000);
if (typeof r.created_at === 'string') {
const ms = Date.parse(r.created_at);
return Number.isNaN(ms) ? null : ms;
}
return null;
}
export function normalizeDispute(raw: unknown): Dispute | null {
if (!isObj(raw)) return null;
const id = typeof raw.id === 'string' ? raw.id : typeof raw.dispute_id === 'string' ? raw.dispute_id : null;
const amountCents = parseAmount(raw);
const createdAtMs = parseCreated(raw);
if (!id || amountCents === null || createdAtMs === null) return null;
return {
id, amountCents, createdAtMs,
status: normalizeStatus(raw.status),
reason: typeof raw.reason === 'string' ? raw.reason : '',
};
}
export function normalizeResponse(body: unknown): Page {
if (!isObj(body) || !Array.isArray(body.data)) throw new Error('Unexpected disputes payload');
const items = body.data.map(normalizeDispute).filter((d): d is Dispute => d !== null);
return { items, hasMore: body.has_more === true };
}
export const cacheKey = (q: Record<string, unknown>) =>
JSON.stringify(Object.keys(q).sort().map((k) => [k, q[k]]));
const matches = (d: Dispute, status: Filter, search: string) =>
(status === 'all' || d.status === status) &&
(search === '' || d.id.toLowerCase().includes(search) || d.reason.toLowerCase().includes(search));
type View = { kind: 'loading' } | { kind: 'error' } | { kind: 'ready'; page: Page };
export function DisputeInbox({ fetchDisputes, pageSize = 10 }: Props) {
const [filter, setFilter] = useState<Filter>('all');
const [searchInput, setSearchInput] = useState('');
const [search, setSearch] = useState('');
const [page, setPage] = useState(1);
const [retryNonce, setRetryNonce] = useState(0);
const [view, setView] = useState<View>({ kind: 'loading' });
const cache = useRef(new Map<string, { value: Page; storedAt: number }>());
const fetchRef = useRef(fetchDisputes);
fetchRef.current = fetchDisputes; // avoids refetch loops when the prop is an inline function
useEffect(() => {
const t = setTimeout(() => {
setSearch(searchInput.trim().toLowerCase());
setPage(1);
}, 250);
return () => clearTimeout(t);
}, [searchInput]);
useEffect(() => {
const query: Query = { status: filter, search, page, pageSize };
const key = cacheKey(query);
const hit = cache.current.get(key);
if (hit && Date.now() - hit.storedAt < TTL_MS) {
setView({ kind: 'ready', page: hit.value });
return;
}
cache.current.delete(key);
const ctrl = new AbortController();
setView({ kind: 'loading' });
fetchRef.current(query, ctrl.signal)
.then((body) => {
if (ctrl.signal.aborted) return;
const parsed = normalizeResponse(body);
const value = { ...parsed, items: parsed.items.filter((d) => matches(d, filter, search)) };
cache.current.set(key, { value, storedAt: Date.now() });
setView({ kind: 'ready', page: value });
})
.catch(() => {
if (!ctrl.signal.aborted) setView({ kind: 'error' });
});
return () => ctrl.abort();
}, [filter, search, page, pageSize, retryNonce]);
return (
<div>
<select value={filter} onChange={(e) => { setFilter(e.target.value as Filter); setPage(1); }}>
<option value="all">All</option>
<option value="needs_response">Needs response</option>
<option value="under_review">Under review</option>
<option value="closed">Closed</option>
</select>
<input value={searchInput} onChange={(e) => setSearchInput(e.target.value)} placeholder="Search" />
{view.kind === 'loading' && <p>Loading...</p>}
{view.kind === 'error' && <button onClick={() => setRetryNonce((n) => n + 1)}>Retry</button>}
{view.kind === 'ready' && view.page.items.length === 0 && <p>No disputes found</p>}
{view.kind === 'ready' && view.page.items.length > 0 && (
<>
<ul>
{view.page.items.map((d) => (
<li key={d.id}>{d.id} | ${(d.amountCents / 100).toFixed(2)} | {d.status}</li>
))}
</ul>
<button disabled={page === 1} onClick={() => setPage((p) => p - 1)}>Prev</button>
<button disabled={!view.page.hasMore} onClick={() => setPage((p) => p + 1)}>Next</button>
</>
)}
</div>
);
}
The inputs live in their own state outside the conditional blocks, so a failed request never clears them. Retry only bumps the counter.
Complexity
- Normalizing a page of n items takes O(n) time and space.
- Building a key costs O(k log k) for k = 3 or 4 parameters, effectively constant. The
Maplookup is O(1). - Memory is O(distinct queries x page size). Expired entries are removed on read, and a long-lived app should add an LRU cap.
Edge cases and trade-offs
amount: 0is valid, so test withtypeof, not truthiness."$1,250.00"needs comma stripping, and"abc"must reject the item rather than renderNaN.- ISO strings without a timezone parse as local time. Prefer explicit
Zand log ambiguous values. - Dropping malformed items keeps the UI clean but can hide data loss, so report the count to logging.
- Filtering client-side on a server-paginated page can leave a page short. If the backend supports the filters, send them as well and keep the client check as a safety net.
Common mistakes
- Using
if (amount), which rejects zero. - Using
Math.floororparseInton dollar amounts, which loses a cent. - Relying on the debounce alone for race safety.
- Putting the fetch function directly in the dependency array, which causes an infinite refetch loop.
- Caching failed responses, so Retry returns the same error.
- Building keys with
JSON.stringify(obj)directly, which depends on property order.