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:

typescript
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.saveCart exactly once with the correct restaurantId and updated lines.
  • A successful add resolves to "ok" and preserves the new line and idempotency key.
  • A rejected add to an initially empty cart restores restaurantId to null, restores lines to the empty array and restores idempotencyKey to null. 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, restaurantId and idempotencyKey.
  • A rollback does not overwrite a newer cart change made while the original request is pending.

Constraints

  • Create only app/lib/cartSync.ts.
  • Import CartLine from ./cart and use the existing useCart store.
  • Export CartApi, addOptimistic and setQtyOptimistic with 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, lines and idempotencyKey before 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 lines can 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:

bash
cd backend && make test W=4O2
cd app && npx tsc --noEmit

Read 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.

Finished Exercise 4.21?

Implementation

Run locally

Write the code in your editor inside zomato-prep, then work through this list.

  1. Create app/lib/cartSync.ts with the required exports.
  2. Apply cart changes before calling CartApi.saveCart.
  3. Snapshot and restore restaurantId, lines and idempotencyKey.
  4. Guard rollback with reference equality.
  5. Preserve the original API error and protect newer cart changes.
  6. Pass make test W=4O2 and npx tsc --noEmit.

Commands

terminal
cd backend && make test W=4O2
terminal
cd app && npx tsc --noEmit

Tests

  • W4 O2 Optimistic cart updates (10 tests) in app-tests/lib/cart-sync.test.ts