Sknoe / Notes
Stopping duplicate orders in storefront Next : why one loading flag isn't enough
A backend-friendly guide to stopping double-taps, race conditions, and duplicate orders in Salesforce Storefront Next.
In Part 1, we saw how Salesforce Storefront Next ties your UI directly to state: change the state, and React updates the screen.
If you come from backend JavaScript—writing SFRA controllers, hooks, or service calls—your first instinct for a loading spinner in React is usually one boolean:
const [isLoading, setIsLoading] = useState(false);
On a fast office laptop, that works fine. Then your feature hits a real store floor or a shopper's phone on bad mobile data.
Three ways a loading flag can fail
Three ugly bugs show up fast:
1. The Double-Tap: Someone taps Confirm Order twice in half a second. Two requests fire. The customer gets booked or charged twice.
2. Impossible UI States: You add isError and isSuccess next to isLoading. Soon a bug leaves isLoading: true and isError: true active at the exact same time.
3. The Network Drop in Limbo: Wi-Fi drops mid-request. Did the partner API create the order or not? If you reset isLoading = false and let the shopper edit their cart and retry, you risk creating two conflicting orders.
A single true/false flag cannot represent reality when an action can succeed, fail cleanly, or land in limbo. To protect your backend from rapid clicks and flaky networks, replace loose booleans with a State Machine.
The five-state submission lifecycle
Instead of guessing from multiple booleans, track your submission flow with one status string:
1. idle
Waiting for the shopper to click submit. Cart and delivery edits are unlocked.
2. pending
Request is in flight. Duplicate clicks are blocked and edits are locked.
3. confirmed
Backend confirmed success. Show the receipt and reset the draft.
4. failed
Server explicitly rejected the request. Nothing was created, so edits unlock safely for a retry.
5. unknown
Timeout or network drop. The backend might have processed it, so retries stay open while edits stay locked.
Pay close attention to failed versus unknown. Only unlock edits when you know nothing was created.
Build the reducer step by step
Let's build this in plain JavaScript first, then connect it to React.
Many developers rely on <button disabled={isLoading}> to stop double-clicks. The catch? Fast double-taps can fire before React finishes re-rendering the disabled button.
Put the guard inside a plain JavaScript function instead:
// Pure JavaScript — no React needed yetfunction handleSubmitRequest(currentState) {// Already in flight or finished? Ignore the extra click.if (currentState.status === 'pending' || currentState.status === 'confirmed') {return currentState;}return {status: 'pending',errorMessage: null,};}
When the first click runs, status flips to 'pending'. If a second click arrives 40 milliseconds later, this function sees 'pending' and ignores it before any fetch() call leaves the browser.
Under the hoodWhy Returning currentState Saves a Re-Render
Looking closer
Because handleSubmitRequest returns currentState untouched on a double-tap, React sees no reference change, avoids unnecessary DOM work, and blocks the duplicate network call immediately.
In React, useReducer takes your current state and an action event, runs them through a switch block, and returns the next state. If you have written a switch (action) block in an SFRA controller or hook, this will feel familiar:
import { useReducer } from 'react';const initialState = {status: 'idle', // 'idle' | 'pending' | 'confirmed' | 'failed' | 'unknown'errorMessage: null,};function orderReducer(state, action) {switch (action.type) {case 'REQUESTED':if (state.status === 'pending' || state.status === 'confirmed') {return state;}return { status: 'pending', errorMessage: null };case 'CONFIRMED':return { status: 'confirmed', errorMessage: null };case 'FAILED':return { status: 'failed', errorMessage: action.message };case 'UNKNOWN':return {status: 'unknown',errorMessage: 'Connection timed out. Please retry without changing details.',};case 'RETRIED':return { status: 'idle', errorMessage: null };default:return state;}}
Notice there are no isLoading or isError flags anywhere. Every event moves status cleanly from one valid state to the next.
Derive UI rules from state
Now your component doesn't need extra canEditCart or isButtonDisabled state variables. Compute them straight from state.status:
export function CheckoutPanel() {const [state, dispatch] = useReducer(orderReducer, initialState);// Derive UI rules directly from the single status stringconst isPending = state.status === 'pending';const isEditLocked = state.status === 'pending' || state.status === 'unknown';const handleConfirmClick = () => {dispatch({ type: 'REQUESTED' });// Next: trigger the API call (we wire up the network & polling loop in Part 3)};return (<div className="checkout-panel"><button type="button" disabled={isEditLocked}>Edit Delivery Window</button>{state.status === 'unknown' && (<p className="warning-banner">{state.errorMessage}</p>)}<buttontype="button"onClick={handleConfirmClick}disabled={isPending || state.status === 'confirmed'}>{isPending ? 'Processing...' : 'Confirm Order'}</button></div>);}
As soon as state.status hits 'pending' or 'unknown', isEditLocked turns true and freezes the Edit Delivery Window button automatically.
How the state machine addresses the three bugs
Remember the three production bugs from the start? Here is how this single status string solves every one of them:
1. The Double-Tap: Blocked synchronously inside case 'REQUESTED' before React even re-renders the button.
2. Impossible UI States: Eliminated. status can only hold one string at a time—never pending and failed together.
3. The Network Drop in Limbo: Solved by separating failed from unknown. When a timeout happens, status moves to 'unknown'—keeping edits locked so any retry sends the exact same order payload.
In Part 3, we wire this exact reducer to a slow third-party API—adding client-generated UUID idempotency keys and a polling loop that recovers cleanly from network drops.
Did this click?
Tap the bulb if this explanation helped.