Live server validation

You can debounce form changes and display the server's current validation response, keeping the item configurator's price tied to its selections.

Learning outcomes

  • Explain why the server owns menu pricing and selection validation.
  • Use local selection rules to prevent unavailable or excessive choices.
  • Debounce a stable selection before requesting a quote.
  • Use TanStack Query to cache quotes and prevent stale prices from being added to the cart.
  • Display selection errors beside their groups and expose accessible option controls.
Prerequisite conceptsTanStack QueryQuery key

When a customer configures a pizza, the price depends on more than its size and selected toppings. The server knows the pricing rules, availability and selection limits. Your Expo app needs to show the price for the customer's current choices without sending a request after every tap.

Week 2 already gave you POST /v1/menu/price. The item configurator uses that endpoint as its source of truth. The phone manages the choices, waits until the customer stops changing them, and displays the server's response. This is server-side validation.

The server's pricing decision

The server knows which sizes an item supports, which options are available and how each selection affects the price. It also applies rules that the menu response might not describe, such as making the cheapest topping free.

Consider a quote from POST /v1/menu/price:

json
{
  "description": "",
  "unit_paise": 0,
  "total_paise": 0,
  "errors": [
    {
      "code": "selection_count",
      "group_id": 10,
      "message": "Choose 1 crust"
    },
    {
      "code": "option_unavailable",
      "group_id": 20,
      "option_id": 203,
      "message": "Paneer is not available in S"
    }
  ]
}

The response contains the server's description, unit price, total and selection errors. Each error is an object with a code and message. It also includes a group_id or option_id when those identifiers apply.

When the errors array is not empty, both unit_paise and total_paise are 0. The server does not return a usable price for an invalid selection.

The app should display these values rather than calculating a competing price.

The same rule applies when the customer changes a size or option. Send the new selection to the endpoint and use the returned quote.

The server remains authoritative even when the app prevents invalid selections locally. This distinction matters because users can send requests outside your screen, and client-side controls cannot guarantee that every request is valid.

Local selection rules

Some rules belong on the phone because they determine how the controls behave. You can implement them as pure functions in app/lib/configurator.ts.

A menu group has min_select and max_select. These fields describe how many options the customer must or may choose.

  • When max_select is 1, render a radio control. Choosing another option replaces the previous choice.
  • When max_select is greater than 1, render a checkbox control. Refuse a new choice when the maximum has already been reached.
  • When an option is out of stock, do not allow the customer to select it.
  • When an option has neither a price for the selected size nor a price for every size through "*", do not allow the customer to select it.

For example, an option can have different prices for different sizes:

ts
const prices = {
  S: 2000,
  M: 3000,
  "*": 1500,
};

const mediumPrice = prices.M ?? prices["*"];
const largePrice = prices.XL ?? prices["*"];

The resulting values are 3000 for Medium and 1500 for a size without a specific price. A size-specific price takes priority over the fallback price.

Availability also depends on stock. Having a matching price does not make an out-of-stock option selectable.

Required single-choice groups need an initial selection. For a group where both min_select and max_select are 1, choose its first available option when initializing the configurator. Other groups do not receive this automatic selection.

A size change can invalidate existing choices. For example, Paneer might be available in Medium but unavailable in Small. Remove that choice when the customer switches to Small.

These rules belong in pure helpers such as controlKind, isAvailable, optionPrice, toggle, initialChosen and dropUnavailable. Returning new objects rather than mutating existing choices also makes state updates predictable.

The rules improve the controls, but they do not replace the server's validation.

The selection in local state

Keep only the customer's actual choices in React state: size and chosen.

The rest of the screen can be derived from these values and the quote. This includes the selection object, price, description, validation errors and whether Add to cart is enabled.

tsx
const [size, setSize] = useState(item.sizes[0].size);
const [chosen, setChosen] = useState<Chosen>(
  () => initialChosen(item, item.sizes[0].size)
);

Build a selection from those values:

tsx
const selection = useMemo(
  () => ({ itemId: item.id, size, chosen, qty: 1 }),
  [item.id, size, chosen]
);

Notice that selection has a stable object identity between changes. It gets a new identity when the item, size or choices change.

This matters because the debounce hook compares the value by reference. Without a stable selection object, an unrelated render could create a new object and restart the timer even though the customer's choices have not changed.

Debouncing selection changes

Imagine a customer selecting three toppings. The screen should not send a pricing request after every tap. Most of those requests would price combinations the customer has already moved past.

Debouncing waits until a value has remained unchanged for a specified period before publishing it. The configurator uses 300 ms.

The generic hook in app/lib/useDebounced.ts maintains a delayed value:

ts
import { useEffect, useState } from "react";

export function useDebounced<T>(value: T, delayMs: number): T {
  const [debounced, setDebounced] = useState(value);

  useEffect(() => {
    const id = setTimeout(() => setDebounced(value), delayMs);
    return () => clearTimeout(id);
  }, [value, delayMs]);

  return debounced;
}

Every value change starts a timer. The effect cleanup cancels the previous timer before the next one starts.

Suppose the customer makes four changes within 300 ms. The first three timers are cancelled. Only the final selection survives long enough to update the debounced value.

This is different from throttling. A throttle limits how frequently a request can happen while changes continue. It can still publish intermediate selections. A debounce waits for the changes to stop.

Query keys and quotes

Once the selection has been debounced, the app can request its quote. TanStack Query manages the request and its cached result.

The query key must include the debounced selection:

tsx
const debounced = useDebounced(selection, 300);

const quote = useQuery({
  queryKey: ["quote", debounced],
  queryFn: () => fetchQuote(api, debounced),
  placeholderData: keepPreviousData,
});

The fetchQuote helper sends the selection through the API client to POST /v1/menu/price. Its request body contains:

json
{
  "item_id": 42,
  "size": "M",
  "chosen": {
    "10": [101],
    "11": [205, 206]
  },
  "qty": 1
}

The IDs here illustrate the request shape. The important part is that the request contains the item, size, selected option IDs and quantity. It does not contain a client-calculated price.

Putting the selection in the query key gives every distinct combination its own cache entry.

This has an important consequence: returning to a selection that was already priced can reuse its cached quote. TanStack Query identifies equivalent query keys by their values, not by requiring the same object reference.

Previous quote data

The keepPreviousData option keeps the previous result visible while the next selection's quote is loading.

This prevents the price area from becoming empty after every tap. However, the previous quote might belong to a different selection.

Consider a customer who selects Medium and then switches to Large. The Medium quote can remain visible while the Large request is pending. That does not make the Medium price valid for Large.

The query key keeps responses associated with their respective selections. A slow response for an older selection cannot replace the result stored under the current selection's key.

This is particularly useful on a phone, where network requests can finish in a different order from the order in which the customer made their choices.

Selection errors

The pricing endpoint can return selection errors in a successful 200 response. A selection error is not necessarily an HTTP failure. It is the server's explanation of why the requested combination is invalid.

For example:

json
{
  "description": "",
  "unit_paise": 0,
  "total_paise": 0,
  "errors": [
    {
      "code": "selection_count",
      "group_id": 10,
      "message": "Choose 1 crust"
    },
    {
      "code": "option_unavailable",
      "group_id": 20,
      "option_id": 203,
      "message": "Paneer is not available in S"
    }
  ]
}

Each entry identifies the error with a code and a human-readable message. A group_id identifies the group involved. An option_id identifies the option when the error concerns a particular option.

When the server returns errors, both price fields are 0. The app must not treat that response as a valid quote for adding an item to the cart.

The app should display each message near the relevant option group. The group_id, rather than the message text or option name, determines where the message belongs.

errorsByGroup checks whether the error's group_id belongs to one of the current item's groups:

  • An error with group_id: 10 belongs under the group whose ID is 10, provided that group belongs to the item.
  • An error with group_id: 20 belongs under the group whose ID is 20, provided that group belongs to the item.
  • An error without a group_id goes into the general error list.
  • An error with a group_id that does not belong to the item also goes into the general error list.

The helper preserves the order of messages within each group and within the general list. It uses the server-provided message for display.

There is one detail about the response shape to account for. The API contract guarantees that errors is always an array, never null. Before the query has returned a quote, however, quote.data is still undefined.

tsx
const errors = quote.data?.errors ?? [];
const mapped = errorsByGroup(item, errors);

This gives the error-mapping helper an empty array before a quote arrives. Once a quote exists, the helper receives the server's array directly.

Keep the different failure types separate:

FailureWhat the app receivesWhat to display
Invalid selection200 with an errors array of objectsMessages beside the relevant groups
HTTP failureAn ApiErrorAn appropriate request error
Network failureA network error such as TypeErrorA connection message

A network failure does not mean the selection is invalid. Keep the previous quote visible when available and display a separate connection message.

Safe quote usage

The customer must not be able to add a line using a quote for an older selection.

There are three conditions to check:

  1. The debounced selection must be the current selection.
  2. The quote request must have finished.
  3. The server must have returned a successful quote without selection errors.

The first condition uses the stable object identity created by useMemo. When debounced === selection, the current selection has survived the debounce period.

The second condition prevents the previous quote from being used while a new request is in flight. The third condition ensures the server accepted the selection.

A quote being present on the screen does not satisfy these conditions. keepPreviousData can preserve a price from an earlier combination.

The cart line should use the quote's unit_paise and description. These values describe what the server priced. The phone does not calculate them independently.

The quoted unit price is a display estimate in the cart. The order flow reprices the items on the server.

Accessible option controls

The configurator uses custom Pressable rows to render radio and checkbox controls. These controls need accessibility information because they are not native form inputs.

tsx
<Pressable
  accessibilityRole={kind}
  accessibilityState={{
    checked: on,
    disabled: !available,
  }}
  disabled={!available}
  onPress={() => setChosen(c => toggle(group, c, option.id))}
>
  <Text>{option.name}</Text>
</Pressable>

The accessibilityRole tells a screen reader whether the row is a radio button or checkbox. The accessibility state reports whether the option is checked and whether it is disabled.

Without this information, the visual control might communicate its state to a sighted customer while a screen reader cannot.

The size chips also need to expose their selected state. Unavailable options should be disabled both visually and through their accessibility state.

The item configurator screen

These ideas come together in the item configurator screen.

The screen reads the item and restaurant IDs from its route params. It uses useMenu(api, restaurantId) to access the menu already cached by the menu screen. Opening the configurator should not trigger another menu request when that data is available.

The screen then presents the available sizes, followed by each option group. Changing a size updates the choices and removes anything that is no longer available.

The quote query responds to the debounced selection. Its errors appear beside their groups, and its unit price appears in the bottom bar.

The key boundary remains clear: the phone controls the selection experience, while the server decides whether the selection is valid and what it costs.

The exercise Item configurator screen brings these pieces together. Your implementation needs to preserve the connection between the current selection, its quote and the cart line. The tests and screen checks verify that connection, including the period when the previous quote remains visible.

Check your understanding

Question 1 of 4

The menu response contains option prices, but the configurator displays the server's unit_paise instead of calculating the total price locally. Why?

Pick an answer, then say how sure you are.

References

Everything above is explained on this page; these are where it comes from (TanStack Query v5, React 19).

Finished Lesson 4.14?