# Replace the Search Transaction module

**Read the Order search state from the InStore State module, and render a replacement for the Search Transactions page built into the InStore POS.**

This page covers the interface that a Search Transaction replacement module implements. For the build setup that every replacement module needs, see [Build a replacement module](/instore/customization/pos-module-development.md).

A Search Transaction replacement module reads [Orders](/api/projects/orders.md) from the Order module context, rather than calling the InStore backend.

## Read Order state and operations

`instoreState/context/OrderModuleContext` provides `useOrderModuleContext`, which returns the Order search state and the operations that act on it.

`useOrderModuleContext` returns the following members. They are marked `@public` in the types that the InStore State module publishes, and are supported for use in replacement modules. To resolve those types, see [Build a replacement module](/instore/customization/pos-module-development.md#resolve-types).

| Member | Type | Description |
| --- | --- | --- |
| `orderSearch` | `OrderSearchPage \ | null` | Most recent page of search results, or `null` before the first search. |
| `selectedOrder` | `OrderModuleOrder \ | null` | Order selected with `loadOrderByNumber`, or `null` when none is selected. |
| `searchOrders` | Method | Searches Orders and stores the page in `orderSearch`. |
| `loadOrderByNumber` | Method | Stores one Order in `selectedOrder`. |
| `clearSearch` | Method | Clears `orderSearch` and `selectedOrder`. Makes no backend call. |

The operations return nothing. They publish results to the state members, so render from `orderSearch` and `selectedOrder` rather than from a return value. Await an operation only to sequence work after it settles.

The provider keeps no record of the criteria behind a page. A module that pages holds its own criteria and sends them again with a new `page` or `offset`.

### Search Orders

`searchOrders` accepts one of two request shapes. The provider determines which one you passed from the field names that are present.

Use the criteria shape to describe what you want, and let the provider build the query:

- `orderNumber`: matched exactly, not as a prefix.
- `customerId`: ID of the Customer on the Order.
- `locationId`: matched against the Order's `custom.fields.locationId`.
- `dateFrom` and `dateTo`: inclusive bounds on `createdAt`, as ISO 8601 strings.
- `page` and `rowsPerPage`: paging. `page` is 1-based. Always send `rowsPerPage` together with `page`

Use the raw query shape for a search that criteria can't express, such as a custom `where` predicate, a different sort, or a wider `expand`. The provider forwards these fields unchanged:

- `where`, `sort`, `expand`, `limit`, `offset`, and `withTotal`.

When you omit these fields, the backend applies the following defaults: `limit` is `10`, `sort` is `createdAt desc`, and `expand` resolves the payment transactions of each Order.

### Handle failures

The `searchOrders` and `loadOrderByNumber` operations both reject when they fail, so wrap each call in `try` and `catch`.

Neither rejection writes to the store. A failed search leaves the previous page on screen. Call `clearSearch` if the previous results shouldn't stay visible.

`loadOrderByNumber` checks the current `orderSearch` page first. When the Order is on that page, the operation doesn't call the backend, can't fail, and may show an older state of the Order. For the freshest data, search again or call `clearSearch` before you load the Order.

## Render a minimal Search Transactions page

Expose a root component that defines your routes:

```tsx title="src/App.tsx"
import React from 'react';
import { Route, Routes } from 'react-router-dom';

import { SearchTransactionPage } from './components/SearchTransactionPage';

const App = () => (
  <Routes>
    <Route index element={<SearchTransactionPage />} />
  </Routes>
);

export default App;
```

Then read the context, look up an Order, and render the result:

```tsx title="src/components/SearchTransactionPage.tsx"
import { useOrderModuleContext } from 'instoreState/context/OrderModuleContext';
import React, { useEffect, useState } from 'react';

const isNotFound = (error: unknown) =>
  (error instanceof Error && error.name === 'OrderNotFoundError') ||
  (typeof error === 'object' &&
    error !== null &&
    (error as { response?: { status?: number } }).response?.status === 404);

export const SearchTransactionPage = () => {
  const { selectedOrder, loadOrderByNumber, clearSearch } =
    useOrderModuleContext();
  const [orderNumber, setOrderNumber] = useState('');
  const [message, setMessage] = useState('');

  // Drop the selected order when the page unmounts, so a stale order
  // doesn't appear the next time the page opens.
  useEffect(() => clearSearch, [clearSearch]);

  const search = async () => {
    const trimmed = orderNumber.trim();
    if (trimmed === '') {
      return;
    }

    setMessage('');
    try {
      await loadOrderByNumber(trimmed);
    } catch (error) {
      clearSearch();
      setMessage(
        isNotFound(error)
          ? 'No order matches that order number.'
          : 'Something went wrong. Try again.',
      );
    }
  };

  return (
    <div>
      <input
        aria-label="Order number"
        value={orderNumber}
        onChange={(event) => setOrderNumber(event.target.value)}
      />
      <button onClick={search}>Search</button>
      {message ? <p role="alert">{message}</p> : null}
      {selectedOrder ? (
        <section>
          <h2>Order {selectedOrder.orderNumber}</h2>
          <ul>
            {selectedOrder.lineItems.map((lineItem) => (
              <li key={lineItem.id}>
                {lineItem.quantity} x {lineItem.variant.sku}
              </li>
            ))}
          </ul>
        </section>
      ) : null}
    </div>
  );
};
```

This example looks up one Order by its number. To show a list of matches, call `searchOrders` with criteria or a query, and render `orderSearch.results`. The example uses plain text for its messages. The translation keys that the POS ships aren't documented on this page, so check the [list of core strings](/instore/customization/list-of-core-strings.md) before you use a key.

## Search Transaction behavior to account for

- Orders aren't normalized. Unlike a Customer, an [Order](/api/projects/orders.md) keeps its shape. Localized values such as `lineItems[].name` are maps keyed by locale, the [Variant](/api/projects/products.md#productvariant) is nested, and [Custom Fields](/api/projects/custom-fields.md) sit under `custom.fields`. Pick the locale and format prices in your module.
- The results live in shared state. `orderSearch` and `selectedOrder` are stored in the shared `transactions` slice, so they survive a remount and a move from a results list to a detail view. Call `clearSearch` when the operator leaves the flow.
- The context has no loading or error state. Track both in your module.
- An empty result is a rejection, not an empty page. Treat `OrdersNotFoundError` and `OrderNotFoundError` as "nothing matched," and treat any other error as a failure that's worth a retry.

> `useOrderModuleContext` does not throw when the Order context is out of scope. It returns `null` state and operations that resolve without doing anything. A wiring issue appears as a search that never finds an Order instead of as a thrown error. Check the module connection first when no results appear.

## Next steps

Use the following resources to finish and roll out your Search Transaction module:

- [Build a replacement module](/instore/customization/pos-module-development.md) to configure Module Federation, resolve types, and read shared POS state.
- [Replace InStore POS UI modules](/instore/customization/pos-ui-modules.md) to register the module and assign it to a location or a workstation.
- [Replace Customer](/instore/customization/pos-customer-module.md) to read Customer state and render a replacement Customer lookup or header control.
- [Run InStore POS API requests](/instore/customization/pos-api-access.md) to set the API host, Project, and tenant, and to get an access token.

## Related pages

- [Area overview page with navigation](/instore.md)
- [Previous page: Replace Customer](/instore/customization/pos-customer-module.md)
- [Next page: Replace Suspended Carts](/instore/customization/pos-suspended-carts-module.md)
- [Search documentation and API specs](/search.md)