Model asynchronous request states
Treat a request as a lifecycle, not just a list
An API is an interface through which software requests data or operations. In a web application, a client can send an HTTP request and receive a status, headers and a body. JSON is a text representation of structured data; parsing it produces JavaScript values, not automatically trusted records. A Promise represents an eventual result or failure. While a request is pending, the UI needs to explain what is happening. Use one explicit status rather than unrelated loading and error flags that can contradict each other. These examples use synthetic responses and a reviewed React client project from Chapter 3; each code block is a separate App.jsx. No network is needed.
import React from 'react';function RequestView({ result }) { switch (result.status) { case 'idle': return <p>Choose a collection.</p>; case 'loading': return <p role="status">Loading specimens…</p>; case 'error': return <p role="alert">Could not load specimens.</p>; case 'success': return result.items.length === 0 ? <p>No specimens found.</p> : <ul>{result.items.map(item => <li key={item.id}>{item.name}</li>)}</ul>; default: return <p>Unknown request state.</p>; }}export default function App() { return <main><h1>Specimens</h1><RequestView result={{status:'success',items:[{id:'m1',name:'Quartz'}]}} /></main>;}Expected: Specimens followed by Quartz. Change the result to {status: "success", items: []} to see the empty message. Empty is a successful response with no matching data, not a failure. Loading, error and idle do not need a data array in this simple model. A production refresh may intentionally preserve earlier results, but label them as previous or refreshing and design that policy explicitly.
Check HTTP status, parse JSON and validate its shape
import React, { useState } from 'react';async function readItems(response) { if (!response.ok) throw new Error('HTTP ' + response.status); const data = await response.json(); if (!Array.isArray(data) || !data.every(x => x && typeof x.id === 'string' && typeof x.name === 'string') || new Set(data.map(x => x.id)).size !== data.length) { throw new Error('Invalid specimen data'); } return data;}export default function App() { const [message,setMessage] = useState('Ready'); async function load() { try { const response = new Response('[{"id":"m1","name":"Quartz"}]', {status:200, headers:{'Content-Type':'application/json'}}); const items = await readItems(response); setMessage(items.map(x => x.name).join(', ') || 'No specimens'); } catch { setMessage('Unable to read specimens.'); } } return <main><button type="button" onClick={load}>Read response</button><p role="status">{message}</p></main>;}Click Read response: Quartz appears. The Response constructor here creates a local fixture, not a server request. In a real approved integration, a fetch call returns a response even for many HTTP failures, such as 404 or 503; check response.ok (successful 2xx status) before reading the expected body. Network failures can reject the fetch promise. JSON parsing can reject separately, and syntactically valid JSON can still have the wrong fields. An endpoint returning 204 has no body: use an endpoint-specific contract instead of always calling json(). Avoid logging private response bodies or credentials. The readItems helper checks required fields and unique IDs; a complete application may require stronger validation.
Retry deliberately after a failure
import React, { useState } from 'react';async function mockRead(attempt) { await Promise.resolve(); if (attempt === 1) throw new Error('Simulated offline connection'); return ['Basalt', 'Quartz'];}export default function App() { const [attempt,setAttempt] = useState(0); const [result,setResult] = useState({status:'idle'}); async function load() { const next = attempt + 1; setAttempt(next); setResult({status:'loading'}); try { setResult({status:'success',items:await mockRead(next)}); } catch { setResult({status:'error'}); } } return <main><h1>Rock collection</h1><button type="button" disabled={result.status === 'loading'} onClick={load}>{result.status === 'error' ? 'Retry' : 'Load specimens'}</button> <p role="status">{result.status === 'loading' ? 'Loading…' : result.status === 'success' ? result.items.join(', ') : ''}</p> {result.status === 'error' && <p role="alert">Connection unavailable. Try again.</p>}</main>;}The first click ends in an error; a second click succeeds with Basalt, Quartz. A pending frame might be too short to see because this fixture settles quickly. There is no automatic retry. A real read can fail while offline or for many unrelated reasons, so avoid asserting that every failure proves the device is offline. For automatic retry, define eligible transient errors, an attempt limit, delay/backoff and cancellation; never blindly repeat a mutation with side effects. The button limits ordinary overlapping clicks in this simple demo, not arbitrary programmatic concurrency. The next lesson deals with competing results.
Practice
Change the synthetic response to 503, malformed JSON, valid JSON with missing fields, and an empty array. Predict whether the error path or empty success path is selected. Explain why parsing and validation are separate.