Persisted cart store

You build the persisted cart store that accepts cart lines for one restaurant and exposes their total in paise. It keeps an idempotency key until the cart is cleared or emptied.

Ticket

Build app/lib/cart.ts as a persisted cart store for the app. It accepts cart lines for one restaurant, exposes the cart total in paise, and owns the idempotency key for the current checkout. Update app/app/(tabs)/_layout.tsx so the Cart tab shows the total quantity as its badge.

The key must survive an app restart. When the customer retries checkout after a crash, the app must send the same key so the API can recognise the request as the same order. The checkout work in the next module depends on this cart state.

Acceptance criteria

  • A cart line has itemId, size, chosen, qty, unitPaise and description. chosen maps group IDs to arrays of option IDs.
  • add(restaurantId, line) appends the line and returns "ok" when the cart is empty or already belongs to that restaurant. When a non-empty cart belongs to another restaurant, it returns "other-restaurant" and leaves the cart unchanged.
  • The first accepted add to an empty cart creates an idempotency key using newKey(). newKey() uses crypto.randomUUID() with a fallback. Later adds and quantity changes keep the existing key.
  • replaceWith(restaurantId, line) replaces the existing cart with the supplied line and creates a new idempotency key.
  • setQty(index, qty) updates the line at that index. A quantity of 0 removes the line. Removing the last line also resets restaurantId and idempotencyKey to null.
  • clear() resets restaurantId and idempotencyKey to null and sets lines to an empty array.
  • total() returns the sum of unitPaise * qty across all cart lines.
  • The store persists under the AsyncStorage name "cart". After restarting the app, the saved restaurant, lines and idempotency key are restored.
  • The Cart tab badge shows the sum of all cart-line quantities. It is hidden when that sum is 0.

Constraints

  • Keep the CartLine fields and types consistent with the quote and order-line data: itemId is a number, size is a string, chosen is Record<string, number[]>, qty and unitPaise are numbers, and description is a string.
  • Keep money in integer paise.
  • Never mutate existing state arrays or objects. Each action must produce new state.
  • Use AsyncStorage for the cart, with the persistence name "cart". Authentication tokens must not go into AsyncStorage.
  • The first render can happen before persisted state is restored. Do not treat the initial empty cart as proof that hydration has finished.

Design direction

Keep the cart state and its actions together in app/lib/cart.ts. Define the cart-line shape there, then keep each action responsible for one state transition. Use Zustand for screen subscriptions and the persistence middleware for storage.

Keep the Cart tab's subscription in app/app/(tabs)/_layout.tsx. Select the total quantity rather than subscribing to the entire cart. A primitive number gives the tab layout a narrower update boundary.

Think about the lifetime of the idempotency key. It identifies one checkout, not one button press. Replacing the cart starts a new checkout, while adding a line or changing a quantity does not. An empty cart has no active checkout.

Persist the cart data rather than trying to persist action functions. AsyncStorage is appropriate for this non-sensitive state, while authentication tokens belong in secure storage. Any layout that meets the contract passes.

How to check your work

Run the 11 exercise tests from the repository root:

bash
cd backend && make test W=4B6

The command runs 5 cart-store tests and 6 cart-persistence tests. Then check the app's TypeScript:

bash
cd app && npx tsc --noEmit

On the emulator or a phone, add a cart line and check that the Cart tab badge shows its quantity. Empty the cart and check that the badge disappears. Restart the app with a saved cart and verify that the badge returns and await AsyncStorage.getItem("cart") contains the same idempotencyKey as before the restart.

When a test fails, read the first failing assertion and compare its expected state with the result of the action it exercised. Fix that state transition before moving on to later failures.

Finished Exercise 4.13?

Shopping cart

2 items

  • 4.12Persisting Zustand statenot completed
  • 4.13Persisted cart storenot completed

Menu configuration and checkout

Up next · Module 5 · 3 items · about 3 h 30 min

Start module 5

Implementation

Run locally

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

  1. Cart lines use the required fields and types.
  2. Cart actions enforce the one-restaurant and idempotency-key rules.
  3. Cart totals are calculated in integer paise.
  4. Cart state persists and restores through AsyncStorage.
  5. Cart tab badge shows the total quantity and disappears when empty.

Commands

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

Tests

  • W4 B6 cart store (5 tests) in app-tests/lib/cart.test.ts
  • W4 B6 cart persistence (6 tests) in app-tests/lib/cart-persist.test.ts