Build a cancellable mock API explorer
Paginate with explicit bounds
Pagination splits results into smaller pages. For a local dataset, slice by a known page size. A real service may use offset, page number or an opaque cursor; follow its contract and do not infer that a full page always means another page exists. Keep page identity in the request, reset it when filters change and keep the previous/next controls consistent with the currently displayed page. The following fixture uses zero-based page indexes internally and two records per page.
import React, { useState } from 'react';function pageOf(items, page, size) { if (!Number.isInteger(page) || page < 0 || !Number.isInteger(size) || size < 1) throw new RangeError('Invalid page'); return {items:items.slice(page * size,(page + 1) * size),hasNext:(page + 1) * size < items.length};}export default function App() { const [page,setPage] = useState(0); const result = pageOf(['Quartz','Basalt','Ammonite'],page,2); return <main><h1>Page {page+1}</h1><ul>{result.items.map(name => <li key={name}>{name}</li>)}</ul> <button type="button" disabled={page === 0} onClick={() => setPage(p => p-1)}>Previous</button> <button type="button" disabled={!result.hasNext} onClick={() => setPage(p => p+1)}>Next</button></main>;}First page: Quartz and Basalt. Next shows Ammonite and disables Next. Previous returns to page one. The example uses unique names as keys only because the fixed fixture has unique names. An empty result has no next page. In a changing dataset, a stale page number can become out of range; decide whether to reset or provide recovery. Cursor-based services can have different navigation constraints.
Inject a mock client with a realistic failure contract
import React, { useState } from 'react';function mockResponse(scenario) { if (scenario === 'offline') throw new TypeError('Simulated network failure'); if (scenario === 'http') return new Response('Unavailable',{status:503}); if (scenario === 'json') return new Response('{bad',{status:200}); return new Response(scenario === 'empty' ? '[]' : '["Quartz"]',{status:200});}export default function App() { const [scenario,setScenario] = useState('ok'); const [message,setMessage] = useState('Ready'); async function inspect() { try { const response = mockResponse(scenario); if (!response.ok) throw new Error('HTTP failure'); const data = await response.json(); if (!Array.isArray(data) || !data.every(x => typeof x === 'string')) throw new Error('Invalid data'); setMessage(data.join(', ') || 'No results'); } catch { setMessage('Unable to load results'); } } return <main><label>Scenario <select value={scenario} onChange={e => {setScenario(e.target.value);setMessage('Ready');}}>{['ok','empty','offline','http','json'].map(s => <option key={s}>{s}</option>)}</select></label> <button type="button" onClick={inspect}>Inspect response</button><p role="status">{message}</p></main>;}This inspector is a sequential manual demonstration: select a scenario, click Inspect response and wait for it to settle before selecting another. It distinguishes successful content and empty data from offline, HTTP and parsing failures. The full explorer below uses a request lifecycle to handle changing selections safely. A synthetic Response can exercise parsing without an actual server, CORS or credentials. Never embed API keys in frontend code or URLs.
Combine pagination, cancellation and retry
import React, { useEffect, useState } from 'react';function mockPage({page,scenario,signal}) { return new Promise((resolve,reject) => { if (signal.aborted) {reject(signal.reason);return;} function abort() {clearTimeout(timer);reject(signal.reason);} const timer = setTimeout(() => { signal.removeEventListener('abort',abort); if (scenario === 'offline') {reject(new TypeError('Simulated network failure'));return;} if (scenario === 'http') {resolve(new Response('Unavailable',{status:503}));return;} if (scenario === 'json') {resolve(new Response('{bad'));return;} const all = scenario === 'empty' ? [] : ['Quartz','Basalt','Ammonite']; resolve(new Response(JSON.stringify({items:all.slice(page*2,page*2+2),hasNext:page*2+2<all.length}))); },300); signal.addEventListener('abort',abort,{once:true}); });}async function decodePage(response) { if (!response.ok) throw new Error('HTTP '+response.status); const data = await response.json(); if (!data || !Array.isArray(data.items) || !data.items.every(x => typeof x === 'string') || new Set(data.items).size !== data.items.length || typeof data.hasNext !== 'boolean') throw new Error('Invalid page'); return data;}function Page({page,scenario,loadPage,onNext,onPrevious}) { const [attempt,setAttempt] = useState(0); const [cancelled,setCancelled] = useState(false); return <section><h2>Page {page+1}</h2> <button type="button" disabled={cancelled} onClick={() => setCancelled(true)}>Cancel / clear result</button>{' '} <button type="button" onClick={() => {setCancelled(false);setAttempt(n=>n+1);}}>Retry</button> {cancelled ? <p role="status">Cancelled.</p> : <Result key={attempt} page={page} scenario={scenario} loadPage={loadPage} onNext={onNext} onPrevious={onPrevious} />} </section>;}function Result({page,scenario,loadPage,onNext,onPrevious}) { const [result,setResult] = useState({status:'loading'}); useEffect(() => { const controller = new AbortController(); let active = true; async function run() { try {const response = await loadPage({page,scenario,signal:controller.signal}); const data = await decodePage(response); if (active) setResult({status:'success',data});} catch {if (active && !controller.signal.aborted) setResult({status:'error'});} } run(); return () => {active=false;controller.abort();}; },[page,scenario,loadPage]); return <><p role="status">{result.status==='loading'?'Loading…':result.status==='success'&&result.data.items.length===0?'No specimens.':''}</p> {result.status==='error'&&<p role="alert">Unable to load. Retry or select another scenario.</p>} {result.status==='success'&&<ul>{result.data.items.map(name=><li key={name}>{name}</li>)}</ul>} <button type="button" disabled={page===0} onClick={onPrevious}>Previous</button> <button type="button" disabled={result.status!=='success'||!result.data.hasNext} onClick={onNext}>Next</button></>;}export default function App() { const [query,setQuery] = useState({page:0,scenario:'ok'}); return <main><h1>Specimen explorer</h1><label>Scenario <select value={query.scenario} onChange={e=>setQuery({page:0,scenario:e.target.value})}>{['ok','empty','offline','http','json'].map(s=><option key={s}>{s}</option>)}</select></label> <Page key={query.scenario+':'+query.page} {...query} loadPage={mockPage} onPrevious={()=>setQuery(q=>({...q,page:Math.max(0,q.page-1)}))} onNext={()=>setQuery(q=>({...q,page:q.page+1}))} /> </main>;}The initial expected result is Quartz and Basalt, then Ammonite on Next. Switching scenario resets the page and creates a new request. Retry remounts Result with a fresh controller; Cancel removes Result and cleanup stops a pending local timer. If already settled, Cancel clears the displayed result rather than undoing the read. The error scenarios intentionally keep failing until changed; retries are manual and no external network is involved. The mock client is injected as a stable function so tests can substitute a controlled implementation. A keyed reset makes loading state correspond to the current query, but also resets local focus and state inside the replaced subtree; production designs should deliberately preserve focus and use an appropriate live announcement strategy.
This project teaches mechanics rather than recommending Effect-based fetching for every production route. Effect requests start on the client after rendering and need manual caching, deduplication and race handling; framework loaders or a dedicated server-state library can coordinate these concerns. Chapter 24 introduces TanStack Query. Test real browser behavior, abort during parsing, accessibility, and any actual service contract independently before release.
Practice
Run through the acceptance checklist with the approved React toolchain. Add a valid JSON object missing hasNext to the mock scenarios and verify it becomes an error. Explain how a real cursor-based endpoint changes the next-page contract.