Order Product Enrichment
Order Product Enrichment
Welcome back. The storefront can now show order history and load an individual order by its ID, which means shoppers already have a solid path from checkout into their order records. In this lesson, you will take that detail experience further by enriching each order item with related product information, so the page can show recognizable product names instead of only raw product IDs.
Previously, you built the order history layer and the first version of order detail loading. That work gave the app two important foundations: a way to fetch primary order data with useOrder(orderId), and a route structure that lets shoppers move from /orders into /orders/[id]. Now you will build on top of that foundation by adding a second, smaller hook that performs derived async enrichment for the line items, and then use that enriched data to make the order detail page feel much more informative.
What This Lesson Adds to the Order Detail Experience
Not all data needed by a page has to come from one API response in a fully display-ready form. In this project, an order already contains its line items, but those line items reference products by product_id. That is enough for the data model to stay compact, but it is not ideal for the user interface because shoppers usually want to recognize products by name, not by an internal identifier.
This lesson introduces a very useful frontend pattern: derived async enrichment. The order is still the primary resource, and useOrder(orderId) remains responsible for loading it. Then a second hook, useOrderProducts(items), looks at the order’s items, extracts the related product IDs, fetches those products, and returns a lookup object that the page can use during rendering. This keeps responsibilities clean: the main hook loads the page’s primary entity, while the enrichment hook adds related display data without taking over the page’s core loading flow.
Building the Product Enrichment Hook
The file src/lib/hooks/useOrderProducts.ts is the main new piece in this lesson. Its job is not to load the order itself. Instead, it accepts the order’s items and turns their product_id values into a lookup object where each key is a product ID and each value is either the fetched Product or null if that related fetch failed.
Here is the start of the hook, where the imports and state are defined:
-
useEffectanduseStateare enough for this hook because it is driven by incomingitemsand needs to store only the final lookup object. There is no separate loading or error state here, because this hook is doing derived enrichment rather than representing the page’s primary request lifecycle. -
The
itemsparameter is optional, which is an important detail. On the first render of the detail page, the order may not exist yet becauseuseOrder(orderId)is still loading, so the enrichment hook needs to behave correctly even when it receivesundefined. -
The state type
Record<string, Product | null>is a very good fit for rendering. Instead of storing products in an array and repeatedly searching with methods like.find(), the page can directly accessproductMap[item.product_id], which makes the consuming code simpler and easier to read. -
Allowing
nullas a value is also intentional. It gives the hook a graceful way to say, “we tried to fetch this related product, but it was unavailable,” without making the whole enrichment process fail.
The next part handles the empty case and sets up the effect lifecycle:
-
The
if (!items?.length)guard is the first thing the effect checks because empty input should be handled immediately. If there are no items, the correct enriched result is simply an empty object, so the hook resetsproductMapto{}and stops early. -
This early return is important for correctness and clarity. It avoids unnecessary asynchronous work and makes the hook’s behavior predictable when the order has no line items or when the primary order data has not arrived yet.
-
The
activeflag is a lightweight stale-update guard. Since the effect contains async work, the component might unmount or theitemsinput might change before the requests finish, and this flag prevents late results from updating state after the effect is no longer current.
Now look at the asynchronous enrichment logic itself:
-
items.map((item) => item.product_id)extracts the related product IDs from the order items. That is the first step in turning order line items into richer display data. -
new Set(...)removes duplicates, which is a very important optimization and correctness habit. If the same product appears in multiple line items, the hook should not fetch that product multiple times just because it is referenced more than once. -
Spreading the set into an array with
[...new Set(...)]produces a de-duplicated list of IDs that can be mapped over normally. This is a clean JavaScript pattern for generating a unique array from repeated values. -
Promise.all(...)is the right choice here because the related products can be fetched in parallel. The hook does not need to wait for one product request to finish before starting the next, so parallel resolution makes the enrichment step faster and keeps the code compact. -
Each mapped async callback returns a tuple shaped like
[productId, product]or[productId, null]. That structure is deliberate because the final goal is not an array of products; it is an object keyed by ID, and these tuples are exactly whatObject.fromEntries(...)expects later. -
The
try/catchinside each mapped request is one of the most important details in this hook. If one product fetch fails, the hook storesnullfor that one ID instead of letting the wholePromise.all(...)reject, which means the order detail page can still render the rest of the enriched line items instead of failing completely.
The final part of the effect applies the result and handles cleanup:
-
if (!active) return;protects the state update from running after the effect is no longer valid. This is especially useful in React because asynchronous work may complete after unmount or after a dependency change starts a newer effect run. -
Object.fromEntries(entries)converts the array of[id, value]tuples into the lookup object the page actually wants. That is why the tuple shape earlier matters so much: it turns the final state update into a single clean transformation. -
void loadProducts();starts the async enrichment without awaiting it inside the effect body. This is the same general pattern you have already used in other custom hooks across the project. -
The cleanup function sets
active = false, which is the mechanism that invalidates late async results. It is a small pattern, but it reflects an important React concept: effects that start async work should also think about what happens if that work finishes after the relevant render context is gone. -
The dependency array is
[items], which means the enrichment reruns whenever the incoming items reference changes. That is exactly what you want, because the product lookup should stay aligned with the current order items and no others. -
Returning only
productMapkeeps the hook focused and intentionally small. This hook is not a general resource manager; it is a specialized enrichment helper, and its narrow API is one of its strengths.
