Sknoe / Notes
Handling Slow APIs in Storefront Next: Client UUIDs and Polling Loops
How to wire your React state machine to slow third-party backends—preventing duplicate orders with client UUIDs and recovering cleanly when networks drop.
In Part 2, we replaced fragile isLoading flags with a 5-state React reducer (idle, pending, confirmed, failed, unknown) that blocks double-taps and freezes edits during timeouts. Now comes the real-world test: what happens when you wire that reducer to a slow backend or third-party API?
In real commerce projects—custom order reservations, ERP syncs, or external booking partners—an API call doesn't always finish in 200 milliseconds. Sometimes it takes 30 seconds, returns 202 Accepted with a job ID, or drops mid-flight on flaky mobile data.
If the shopper retries after a timeout, three things must happen:
The backend must recognize it is the exact same order—not a brand-new purchase.
The browser must poll safely without stacking overlapping timers or leaking memory if the shopper navigates away.
Every network outcome must map cleanly into CONFIRMED, FAILED, or UNKNOWN.
1. Preventing Duplicates Across Retries: The Client UUID
Your reducer blocks rapid double-clicks in the browser. What if the network drops after the request reaches the server, and the shopper taps Retry 10 seconds later?
To make retries safe, the browser generates a unique idempotency key (crypto.randomUUID()) the moment the shopper starts a submission—and reuses that exact same key on every retry until the order is confirmed or the shopper edits the cart.
Here is how you hold that key in CheckoutPanel alongside your reducer:
import { useRef, useReducer } from 'react';// Inside CheckoutPanel:const idempotencyKeyRef = useRef(crypto.randomUUID());// Generate a fresh key ONLY when the shopper unlocks and edits the orderconst resetSubmissionKey = () => {idempotencyKeyRef.current = crypto.randomUUID();};
Notice we store the key in useRef rather than useState—updating a ref never triggers an unnecessary re-render, and its value stays stable across retries.
2. Firing the Request and Mapping Outcomes to Your Reducer
When the shopper clicks Confirm Order, we dispatch REQUESTED, send the payload with Idempotency-Key, and translate the response into one of our reducer actions:
async function submitOrder(payload, idempotencyKey, dispatch) {dispatch({ type: 'REQUESTED' });try {const response = await fetch('/api/orders/confirm', {method: 'POST',headers: {'Content-Type': 'application/json','Idempotency-Key': idempotencyKey,},body: JSON.stringify(payload),signal: AbortSignal.timeout(8000), // Don't hang forever});// 4xx validation or business rejection -> safe to unlock editsif (response.status >= 400 && response.status < 500) {const errorData = await response.json();dispatch({ type: 'FAILED', message: errorData.message || 'Order rejected.' });return;}// 5xx server error -> backend might have processed it, keep edits lockedif (!response.ok) {dispatch({ type: 'UNKNOWN' });return;}const data = await response.json();// 200 OK -> finished immediatelyif (data.status === 'CONFIRMED') {dispatch({ type: 'CONFIRMED' });return;}// 202 Accepted -> backend is still processing; start pollingif (data.jobId) {await pollOrderStatus(data.jobId, dispatch);}} catch (error) {// Network drop or AbortSignal timeout -> move to 'unknown' (edits stay locked)dispatch({ type: 'UNKNOWN' });}}
Look at how clean that boundary is:
4xx error: Server explicitly said “No.” We dispatch FAILED so edits unlock.
5xx error or network timeout: Outcome is uncertain. We dispatch UNKNOWN so edits stay locked while the shopper retries with the same idempotencyKey.
202 Accepted (data.jobId): The server accepted the job and handed back a tracking ID—so we transition into a controlled polling loop.
3. Building a Safe Polling Loop (Without Timer Leaks)
A naive setInterval polling loop causes two classic React bugs: overlapping requests when the network is slow, and zombie requests that keep running after the user leaves the page.
Use a sequential while loop with AbortController instead—each check waits for the previous one to finish before sleeping:
async function pollOrderStatus(jobId, dispatch, signal) {const maxAttempts = 15;const delayMs = 2000;for (let attempt = 1; attempt <= maxAttempts; attempt++) {// Stop immediately if the component unmounted or user navigated awayif (signal?.aborted) return;try {const response = await fetch(`/api/orders/status/${jobId}`, { signal });if (response.ok) {const result = await response.json();if (result.status === 'CONFIRMED') {dispatch({ type: 'CONFIRMED' });return;}if (result.status === 'FAILED') {dispatch({ type: 'FAILED', message: result.message || 'Order failed.' });return;}}} catch (error) {if (error.name === 'AbortError') return;// Ignore transient blips during polling and keep trying until maxAttempts}// Wait 2 seconds before the next checkawait new Promise((resolve) => setTimeout(resolve, delayMs));}// Reached maxAttempts without a final answer -> move to 'unknown'dispatch({ type: 'UNKNOWN' });}
Under the hoodWhy a for Loop Beats setInterval for API Polling
Looking closer
On a slow mobile connection, a status check might take 3 seconds. setInterval would stack multiple concurrent requests out of order. A sequential for loop with await guarantees that the 2-second pause starts after the previous response arrives—and wiring AbortController cancels pending fetches the moment the component unmounts.
4. Putting the Full Series Together
Across these three parts, you now have the complete mental model and production pattern for moving from SFRA to Salesforce Storefront Next:
Part 1 — State-Driven Views: Replace Controller -> pdict -> ISML round-trips with route loader() functions, action() mutations, and state-driven React components (UI = f(state)).
Part 3 — Idempotent APIs & Safe Polling: Pair your reducer with a useRef UUID Idempotency-Key and an AbortController-backed polling loop so slow backends and dropped connections never create duplicate orders.
Did this click?
Tap the bulb if this explanation helped.
Interview questions
What problem does an idempotency key solve when an order request times out?
It gives the server a stable identifier for one logical order attempt. If the server stores the key with the result, a retry using the same key can return the original result instead of creating another order. Sending the header only works if the endpoint implements that contract.
Why should a client reuse the same idempotency key on a retry but generate a new one after the shopper changes the cart?
A retry is the same logical operation, so the same key lets the server recognize it and return the original result. Changed order details represent a new operation and need a new key so the server does not mistake them for the earlier order.
Why can sequential polling be safer than using setInterval for a slow API?
A sequential loop awaits each status request and then waits before starting the next one. If a request takes longer than the interval, setInterval can start another request before the first finishes, creating overlapping checks. An AbortSignal can stop browser-side polling when the view is no longer needed.
When should a checkout classify an order request as FAILED rather than UNKNOWN?
Use FAILED only when the endpoint contract confirms the request was rejected and no order was created. A timeout or other ambiguous result should be UNKNOWN because the server may have processed the order; a retry should use the same idempotency key.
Does AbortController guarantee that an order was cancelled on the server?
No. It aborts the browser request or stops client-side polling, but the server may already be processing the request. The client must treat an uncertain result as UNKNOWN and use the same idempotency key or query the server for the operation status.