Cart synchronization helper
You build cart synchronization helpers that update the Zustand cart immediately and save its restaurant ID and lines through CartApi. Failed saves restore the previous state without overwriting newer cart changes.
Ticket
Build app/lib/cartSync.ts with addOptimistic and setQtyOptimistic. Both functions update the existing Zustand cart before sending its updated restaurant ID and lines to CartApi.
Export these declarations:
export type CartApi = {
saveCart(cart: { restaurantId: number | null; lines: CartLine[] }): Promise<void>;
};
export async function addOptimistic(api: CartApi, restaurantId: number, line: CartLine): Promise<"ok" | "other-restaurant">;
export async function setQtyOptimistic(api: CartApi, index: number, qty: number): Promise<void>;The customer app needs the cart to respond immediately when a customer adds an item or changes a quantity. If the server rejects the update, restore the previous cart. A failed request must also preserve the original idempotency key so a later order submission retains its request identity.
Acceptance criteria
- Adding a cart line updates the Zustand store immediately, before the server responds.
- Adding a cart line calls
api.saveCartexactly once with the correctrestaurantIdand updatedlines. - A successful add resolves to
"ok"and preserves the new line and idempotency key. - A rejected add to an initially empty cart restores
restaurantIdtonull, restoreslinesto the empty array and restoresidempotencyKeytonull. The function rethrows the original error. - A rejected add to an existing cart restores the original lines and existing idempotency key.
- Adding a line for another restaurant resolves to
"other-restaurant"without calling the API or changing the cart. - Changing a quantity updates the Zustand store immediately and sends the updated quantity to the server.
- A rejected quantity change restores the previous quantity.
- A rejected removal of the last cart line restores the original line,
restaurantIdandidempotencyKey. - A rollback does not overwrite a newer cart change made while the original request is pending.
Constraints
- Create only
app/lib/cartSync.ts. - Import
CartLinefrom./cartand use the existinguseCartstore. - Export
CartApi,addOptimisticandsetQtyOptimisticwith the signatures above. - Do not create another cart store or introduce React dependencies.
- Do not modify
app/lib/cart.ts, the provided tests or the test fakes. - Snapshot
restaurantId,linesandidempotencyKeybefore mutating the store. - Rethrow the same error received from the rejected API call.
Design direction
Keep both synchronization helpers in app/lib/cartSync.ts. Use the existing useCart methods for cart mutations instead of duplicating their logic. Keep snapshot and rollback responsibilities separate so both operations follow the same recovery rules.
Consider these trade-offs:
- An optimistic update makes the UI respond before the server confirms the change. It improves perceived responsiveness but requires recovery when saving fails.
- A snapshot should preserve the entire state needed for recovery. Restoring only
linescan leave the cart with an incorrect restaurant ID or a missing idempotency key. - Reference equality provides a guard against stale optimistic rollback. It prevents an older failed operation from replacing a newer cart edit. It does not coordinate every possible overlap between pending server requests.
Any layout that meets the contract passes.
How to check your work
Run the exercise tests and then the TypeScript check:
cd backend && make test W=4O2
cd app && npx tsc --noEmitRead the first failing assertion before changing code. It identifies whether the failure concerns immediate updates, the saved cart, rollback state or protection against newer changes.
The reference solution passes every check for this exercise. Try the hints first; reading the answer before you have struggled with the problem teaches much less.
Implementation
Run locally
Write the code in your editor inside zomato-prep, then work through this list.
- Create
app/lib/cartSync.tswith the required exports. - Apply cart changes before calling
CartApi.saveCart. - Snapshot and restore
restaurantId,linesandidempotencyKey. - Guard rollback with reference equality.
- Preserve the original API error and protect newer cart changes.
- Pass
make test W=4O2andnpx tsc --noEmit.
Commands
cd backend && make test W=4O2cd app && npx tsc --noEmitTests
W4 O2 Optimistic cart updates (10 tests)inapp-tests/lib/cart-sync.test.ts