Rider mode and customer tracking screens
You build rider mode and the customer tracking screen, connecting rider offers and location updates to a live order map and status timeline.
Ticket
Build rider mode and the customer tracking screen in the Expo app. Put reusable socket, rider and tracking logic in app/lib, then connect those libraries to the native screens.
The rider needs to go online, report their location, receive an offer and move an order through pickup and delivery. The customer needs to see the restaurant and rider on a map while order events update the status timeline. Both screens must keep working through a temporary API outage without restarting the app.
The tests call these exact functions:
export function nextDelay(attempt: number, random?: () => number): number
export function socketUrl(apiBase: string, token: string): string
export function useOrderSocket(url: string | null, onMessage: (raw: string) => void): { connected: boolean }
export type Offer = { orderId: number; expiresAt: number }
export function offerSecondsLeft(expiresAt: number, now: number): number
export function riderAction(status: string): { label: string; event: "PICK_UP" | "DELIVER" } | null
export function locationBody(pos: { coords: { latitude: number; longitude: number } }): { lat: number; lng: number }
export function parseOffer(raw: string): Offer | null
export type OrderSocketEvent = { order_id: number; event_id: string; from: string; to: OrderStatus }
export type SocketMessage = { kind: "event"; event: OrderSocketEvent } | { kind: "location"; lat: number; lng: number } | { kind: "offer"; orderId: number; expiresAt: number }
export function parseSocketMessage(raw: string): SocketMessage | null
export function applyEvent(order: OrderDetail, ev: OrderSocketEvent, now?: () => number): OrderDetailAcceptance criteria
-
socketUrlconvertshttptowsandhttpstowss, removes one trailing slash from the API base, appends/v1/ws, and URL-encodes the token. For example:socketUrl('http://192.168.1.5:8080', 'abc')returnsws://192.168.1.5:8080/v1/ws?token=abc.socketUrl('https://api.example.com', 'abc')returnswss://api.example.com/v1/ws?token=abc.socketUrl('http://localhost:8080/', 'abc')returnsws://localhost:8080/v1/ws?token=abc.socketUrl('http://localhost:8080', 'a b&c=d')returnsws://localhost:8080/v1/ws?token=a%20b%26c%3Dd.
-
nextDelayusesMath.min(30000, 1000 * 2 ** attempt) * (0.5 + random()), withMath.randomas the default random function. It doubles the base delay until the 30000 ms cap applies, then adds jitter. The following results must hold:nextDelay(0, () => 0.5)returns1000.nextDelay(1, () => 0.5)returns2000.nextDelay(3, () => 0.5)returns8000.nextDelay(10, () => 0.5)andnextDelay(20, () => 0.5)both return30000.nextDelay(2, () => 0)returns2000.nextDelay(2, () => 0.999)returns approximately5996.
-
useOrderSocketopens the WebSocket insideuseEffectand returns{ connected: boolean }. Keep the latestonMessagecallback in a ref so callback changes do not restart the socket effect. Reconnect after a socket closes usingnextDelay, reset the attempt counter after a successful open, and clear pending timers and close the socket during cleanup. No reconnection may be scheduled after unmount. -
offerSecondsLeftrounds the remaining time up and never returns a negative value. ForofferSecondsLeft(30_000, now), the results must be30whennowis0,30whennowis100,1whennowis29_001, and0whennowis30_000. It must also return0whennowis45_000. -
riderActionreturns{ label: "Picked up", event: "PICK_UP" }forREADYand{ label: "Delivered", event: "DELIVER" }forPICKED_UP. It returnsnullforPLACED,ACCEPTED,PREPARING,DELIVERED,CANCELLEDandREJECTED. -
locationBodyconverts device coordinates into the API payload. For latitude28.4601and longitude77.0302, it returns{ lat: 28.4601, lng: 77.0302 }. -
parseOfferaccepts a JSON message withkind: "offer",order_idandexpires_at, converting the field names toorderIdandexpiresAt. For{"kind":"offer","order_id":9,"expires_at":1760000030000}, it returns{ orderId: 9, expiresAt: 1760000030000 }. It returnsnullfor invalid JSON, other message kinds, missingorder_idor missingexpires_at. -
applyEventapplies an event for order9withevent_id: "e3",from: "ACCEPTED"andto: "PREPARING"by returning a new order with statusPREPARINGand three events. The appended event must containevent_id: "e3",from_status: "ACCEPTED",to_status: "PREPARING"andcreated_at: "2026-11-18T10:05:00.000Z"when the supplied clock returnsDate.parse('2026-11-18T10:05:00Z'). -
applyEventmust not mutate the original order or its existing events array. It returns the original order object when the event belongs to another order, such asorder_id: 10, or when the event ID already exists, such asevent_id: "e2". -
parseSocketMessagereturns{ kind: "event", event: ... }for{"order_id":9,"event_id":"e3","from":"ACCEPTED","to":"PREPARING"}. -
parseSocketMessagereturns{ kind: "location", lat: 28.4601, lng: 77.0302 }for{"lat":28.4601,"lng":77.0302}. -
parseSocketMessagereturns{ kind: "offer", orderId: 9, expiresAt: 1760000030000 }for{"kind":"offer","order_id":9,"expires_at":1760000030000}. -
parseSocketMessagereturnsnullfor invalid JSON, unknown message shapes, non-object values and location messages with non-numeric coordinates. This includesnope,{"hello":"world"},{"lat":"x","lng":1}and42. -
The rider screen provides a rider mode switch for users with the
riderrole. Enabling online mode requests foreground location permission before starting location updates. It useswatchPositionAsyncwith a4000ms interval and converts every position throughlocationBodybefore sending it. -
The rider screen displays incoming offers in an offer card with a 30-second countdown based on the offer's expiration timestamp. It provides an Accept button and displays Picked up or Delivered actions according to the current order status.
-
The customer screen renders a
MapViewwith a restaurant marker and displays a rider marker when location is available. On Android, it usesanimateMarkerToCoordinateto move the existing marker to each new position instead of rebuilding the map. -
The customer status timeline updates from incoming socket events using the existing order event and status types.
-
Manual check: Complete the rider and customer workflow on a phone and emulator. Place an order, accept it, mark it ready, receive and accept the offer, pick it up, watch the rider marker move, and deliver the order without restarting either app.
-
Manual check: Stop the API for 20 seconds and restart it. The customer tracking screen must reconnect without restarting the app.
Constraints
- Use the specified capped exponential delay formula with a
30000ms maximum base delay and the0.5 + random()jitter factor. - Use
Math.randomwhen no random function is supplied. - Use a
4000ms location update interval. - Calculate the countdown with ceiling and a zero minimum.
- Use the server-provided offer expiration timestamp instead of assuming every received offer has a fresh 30 seconds remaining.
Design direction
Keep the pure logic in app/lib/useSocket.ts, app/lib/rider.ts and app/lib/tracking.ts. Keep native permissions, location subscriptions, buttons and map components in the screens. Reuse OrderDetail, OrderEvent and OrderStatus from app/lib/orders.ts.
Treat the socket hook as a lifecycle boundary. Keep its latest message handler in a ref, while the socket effect owns the connection, reconnect timer and cleanup. This prevents a render from unnecessarily restarting an active connection.
Keep rider calculations independent of React Native. The helpers should accept ordinary data and return predictable results. Use the existing Zustand store for state that needs to be shared or persisted, rather than duplicating order state in a second store.
The customer map should update the existing rider marker when a location message arrives. Avoid rebuilding the entire MapView for every coordinate. The existing order tab uses Polling every 10 seconds, but live tracking should use the socket stream for immediate updates.
Any layout that meets the contract passes. Consider whether a value belongs in a pure helper or a screen, whether a callback change should recreate a socket, and whether an irrelevant or duplicate event should produce a new order object.
How to check your work
Run the backend exercise tests:
cd backend && make test W=5B6Run the TypeScript library tests:
cd app-tests && npx jest lib/socket lib/rider lib/trackingRun the application TypeScript check:
cd app && npx tsc --noEmitRead the first failing assertion to identify the failing contract: socket URL or retry delay, rider countdown or payload conversion, or tracking message parsing and event application. Then test the native screens manually on a phone and emulator, including the API restart.
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.
- The socket URL and capped reconnect delay helpers pass their tests.
- The socket hook reconnects after closure and cleans up on unmount.
- Rider helpers handle countdowns, actions, location payloads and offers correctly.
- Tracking helpers parse messages and apply events without mutating existing orders.
- Rider mode supports location updates, offers, pickup and delivery.
- The customer map animates rider movement and updates the order timeline.
Commands
cd backend && make test W=5B6cd app-tests && npx jest lib/socket lib/rider lib/trackingcd app && npx tsc --noEmitTests
W5 B6 reconnect backoff (7 tests)inapp-tests/lib/socket.test.tsW5 B6 rider mode (8 tests)inapp-tests/lib/rider.test.tsW5 B6 live order tracking (8 tests)inapp-tests/lib/tracking.test.ts