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,unitPaiseanddescription.chosenmaps 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
addto an empty cart creates an idempotency key usingnewKey().newKey()usescrypto.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 of0removes the line. Removing the last line also resetsrestaurantIdandidempotencyKeytonull.clear()resetsrestaurantIdandidempotencyKeytonulland setslinesto an empty array.total()returns the sum ofunitPaise * qtyacross 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
CartLinefields and types consistent with the quote and order-line data:itemIdis a number,sizeis a string,chosenisRecord<string, number[]>,qtyandunitPaiseare numbers, anddescriptionis 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:
cd backend && make test W=4B6The command runs 5 cart-store tests and 6 cart-persistence tests. Then check the app's TypeScript:
cd app && npx tsc --noEmitOn 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.
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.
Shopping cart
2 items
- 4.12Persisting Zustand statenot completed
- 4.13Persisted cart storenot completed
Up next · Module 5 · 3 items · about 3 h 30 min
Implementation
Run locally
Write the code in your editor inside zomato-prep, then work through this list.
- Cart lines use the required fields and types.
- Cart actions enforce the one-restaurant and idempotency-key rules.
- Cart totals are calculated in integer paise.
- Cart state persists and restores through AsyncStorage.
- Cart tab badge shows the total quantity and disappears when empty.
Commands
cd backend && make test W=4B6cd app && npx tsc --noEmitTests
W4 B6 cart store (5 tests)inapp-tests/lib/cart.test.tsW4 B6 cart persistence (6 tests)inapp-tests/lib/cart-persist.test.ts