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:

ts
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): OrderDetail

Acceptance criteria

  • socketUrl converts http to ws and https to wss, 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') returns ws://192.168.1.5:8080/v1/ws?token=abc.
    • socketUrl('https://api.example.com', 'abc') returns wss://api.example.com/v1/ws?token=abc.
    • socketUrl('http://localhost:8080/', 'abc') returns ws://localhost:8080/v1/ws?token=abc.
    • socketUrl('http://localhost:8080', 'a b&c=d') returns ws://localhost:8080/v1/ws?token=a%20b%26c%3Dd.
  • nextDelay uses Math.min(30000, 1000 * 2 ** attempt) * (0.5 + random()), with Math.random as 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) returns 1000.
    • nextDelay(1, () => 0.5) returns 2000.
    • nextDelay(3, () => 0.5) returns 8000.
    • nextDelay(10, () => 0.5) and nextDelay(20, () => 0.5) both return 30000.
    • nextDelay(2, () => 0) returns 2000.
    • nextDelay(2, () => 0.999) returns approximately 5996.
  • useOrderSocket opens the WebSocket inside useEffect and returns { connected: boolean }. Keep the latest onMessage callback in a ref so callback changes do not restart the socket effect. Reconnect after a socket closes using nextDelay, 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.

  • offerSecondsLeft rounds the remaining time up and never returns a negative value. For offerSecondsLeft(30_000, now), the results must be 30 when now is 0, 30 when now is 100, 1 when now is 29_001, and 0 when now is 30_000. It must also return 0 when now is 45_000.

  • riderAction returns { label: "Picked up", event: "PICK_UP" } for READY and { label: "Delivered", event: "DELIVER" } for PICKED_UP. It returns null for PLACED, ACCEPTED, PREPARING, DELIVERED, CANCELLED and REJECTED.

  • locationBody converts device coordinates into the API payload. For latitude 28.4601 and longitude 77.0302, it returns { lat: 28.4601, lng: 77.0302 }.

  • parseOffer accepts a JSON message with kind: "offer", order_id and expires_at, converting the field names to orderId and expiresAt. For {"kind":"offer","order_id":9,"expires_at":1760000030000}, it returns { orderId: 9, expiresAt: 1760000030000 }. It returns null for invalid JSON, other message kinds, missing order_id or missing expires_at.

  • applyEvent applies an event for order 9 with event_id: "e3", from: "ACCEPTED" and to: "PREPARING" by returning a new order with status PREPARING and three events. The appended event must contain event_id: "e3", from_status: "ACCEPTED", to_status: "PREPARING" and created_at: "2026-11-18T10:05:00.000Z" when the supplied clock returns Date.parse('2026-11-18T10:05:00Z').

  • applyEvent must not mutate the original order or its existing events array. It returns the original order object when the event belongs to another order, such as order_id: 10, or when the event ID already exists, such as event_id: "e2".

  • parseSocketMessage returns { kind: "event", event: ... } for {"order_id":9,"event_id":"e3","from":"ACCEPTED","to":"PREPARING"}.

  • parseSocketMessage returns { kind: "location", lat: 28.4601, lng: 77.0302 } for {"lat":28.4601,"lng":77.0302}.

  • parseSocketMessage returns { kind: "offer", orderId: 9, expiresAt: 1760000030000 } for {"kind":"offer","order_id":9,"expires_at":1760000030000}.

  • parseSocketMessage returns null for invalid JSON, unknown message shapes, non-object values and location messages with non-numeric coordinates. This includes nope, {"hello":"world"}, {"lat":"x","lng":1} and 42.

  • The rider screen provides a rider mode switch for users with the rider role. Enabling online mode requests foreground location permission before starting location updates. It uses watchPositionAsync with a 4000 ms interval and converts every position through locationBody before 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 MapView with a restaurant marker and displays a rider marker when location is available. On Android, it uses animateMarkerToCoordinate to 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 30000 ms maximum base delay and the 0.5 + random() jitter factor.
  • Use Math.random when no random function is supplied.
  • Use a 4000 ms 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:

bash
cd backend && make test W=5B6

Run the TypeScript library tests:

bash
cd app-tests && npx jest lib/socket lib/rider lib/tracking

Run the application TypeScript check:

bash
cd app && npx tsc --noEmit

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

Finished Exercise 5.12?

Implementation

Run locally

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

  1. The socket URL and capped reconnect delay helpers pass their tests.
  2. The socket hook reconnects after closure and cleans up on unmount.
  3. Rider helpers handle countdowns, actions, location payloads and offers correctly.
  4. Tracking helpers parse messages and apply events without mutating existing orders.
  5. Rider mode supports location updates, offers, pickup and delivery.
  6. The customer map animates rider movement and updates the order timeline.

Commands

terminal
cd backend && make test W=5B6
terminal
cd app-tests && npx jest lib/socket lib/rider lib/tracking
terminal
cd app && npx tsc --noEmit

Tests

  • W5 B6 reconnect backoff (7 tests) in app-tests/lib/socket.test.ts
  • W5 B6 rider mode (8 tests) in app-tests/lib/rider.test.ts
  • W5 B6 live order tracking (8 tests) in app-tests/lib/tracking.test.ts