@simpleapps-com/augur-hooks
React Query hooks and Zustand stores for Augur data. The main entry needs no DOM and no react-dom, so it works in Next.js and React Native alike.
pnpm add @simpleapps-com/augur-hooksPeer dependencies: react 19, @tanstack/react-query 5, @tanstack/react-query-persist-client 5, zustand 5 and @simpleapps-com/augur-api. Every export, with its description: API Reference.
Entry points
| Import | Runs in | Purpose |
|---|---|---|
@simpleapps-com/augur-hooks |
Anywhere | Provider, useAugurOptions, named hooks, stores, persistence |
@simpleapps-com/augur-hooks/server |
Server components | getQueryClient, createAugurOptions, executeBatchQuery |
@simpleapps-com/augur-hooks/web |
Browser | useIsMobile, useIsHydrated, MobileProvider, useMobileOptimizedIntersection, useImageWithFallback |
@simpleapps-com/augur-hooks/checkout |
Browser | createCheckoutProvider, ORDER_CONFIRMATION_KEY |
Provider
AugurHooksProvider gives every hook the SDK, auth, cache config and site config. All props but children are optional.
import { AugurHooksProvider } from "@simpleapps-com/augur-hooks";
<AugurHooksProvider api={api} auth={authContext} cache={cacheConfig} site={siteConfig}>
<App />
</AugurHooksProvider>;The proxy useAugurOptions() returns is chosen once, when the provider builds it:
- With an
api:createOptionsProxy(api), soqueryFncalls the SDK. - Without one, when a query action is registered (importing
@simpleapps-com/augur-server/hooksregisters one;registerQueryActiondoes it by hand):createQueryActionProxy, soqueryFncalls the server. - Otherwise: keys only, and each
queryFnthrows until you override it at the call site.
Sites built on defineSite() can use augur-web's AugurSiteProvider, which wraps this provider with analytics. useAugurApi, useAugurApiOptional, useAugurAuth, useAugurCache and useAugurSite read the provider's values.
The options proxy
useAugurOptions() mirrors the SDK. Each read method gives query options and each write gives mutation options, with the cache tier and a deterministic key filled in by augur-core:
import { useAugurOptions } from "@simpleapps-com/augur-hooks";
import { useMutation, useQuery } from "@tanstack/react-query";
function ProductPage({ invMastUid, customerId }: { invMastUid: number; customerId: number }) {
const q = useAugurOptions();
const { data: item } = useQuery(q.items.invMast.doc.get(invMastUid));
const { data: stock } = useQuery(q.items.invMast.stock.get(invMastUid));
const { data: price } = useQuery(q.pricing.priceEngine.list({ itemId: "SKU-1", customerId }));
const addLine = useMutation(q.commerce.cartLine.add.create());
}data is the SDK response's data, already unwrapped. The keys are the same on the server and in the browser, so prefetched data hydrates.
A read by path id (a get called with its id first, such as doc.get(invMastUid)) answers a missing record as null (typed T | null) instead of failing, whether the options come from an SDK client, the registered query action or fetch mode; every other failure still fails the query (augur-server, queryAction).
Prefetching on the server
import { createAugurOptions, getQueryClient } from "@simpleapps-com/augur-hooks/server";
const queryClient = getQueryClient(); // one per request (React cache())
const q = createAugurOptions(site.client, cacheConfig);
await queryClient.prefetchQuery(q.items.invMast.doc.get(invMastUid));createAugurOptions takes an SDK client, a query action function, or nothing; with nothing it uses the registered query action and throws if there is none.
Clearing the user's own data after a write
The server never caches what a user changes, their wishlists and favorites (augur-core's user tier). The browser keeps it for a minute, so a site should clear that copy when the user's own write succeeds. Give the browser's QueryClient a MutationCache with userWriteClearing:
import { MutationCache, QueryClient } from "@tanstack/react-query";
import { userWriteClearing } from "@simpleapps-com/augur-hooks";
const queryClient: QueryClient = new QueryClient({
mutationCache: new MutationCache(userWriteClearing(() => queryClient)),
});After a successful mutation it invalidates the cached reads that share a user namespace with it (augur-core's clearedBy): a wishlist write refetches the wishlists and their lines, and a favorites write leaves the wishlists alone. It reads the method path from the keys, so it works for mutations and reads keyed by their SDK path, as the options proxy keys them. clearUserReadsOnWrite(queryClient, mutationKey) does the same for one write.
Named hooks
| Hook | Does |
|---|---|
useCartActions(callbacks) |
Optimistic cart changes with rollback; callbacks supplies addToCart, updateCartLines, deleteItemsFromCart (each resolving true on success) and an optional toast; refetches the cart after every change; addToCart refuses an item without a quantity or with a blank unit of measure |
useCartInitialization(session, callbacks) |
Resolves the cart header from the session (signed in) or a cookie (guest); call once in the root layout |
useCartPricing({ customerId?, queryFn? }) |
Prices every cart line at its quantity and in its unit of measure, so price breaks and case prices apply (a custom queryFn gets the unit as its fourth argument); returns each line's own price (getLineUnitPrice(index), getLineTotal(index): one item on two lines keeps two prices), the subtotal, and the loading state over the prices it fetches. The customer is the first usable one of the option, the session and the site default (augur-utils resolveAddressId): "" and "0" never price customer 0 |
usePaymentFlow(…) |
The payment sequence: transaction setup, card info, validation, account query, billing update |
useTaxEstimate(lines, shipTo) |
Sales tax through augur-server's estimateTax server action (payments.rates.create): { tax, isLoading, error }. Asks only with a ship-to postal code and every line priced, and builds the body itself (ratesBodyOf); never throws, never cached. Build lines from the cart with taxLinesOf(cartLines, useCartPricing()), which prices a line only once its price has loaded |
useTokenizeCard() |
A mutation over augur-server's tokenizeCard server action: mutateAsync(elementBodyOf(card, billing, shipping)) resolves to TElementToken, after the server's card checks |
useStock(invMastUid, options?) |
Stock for one item, resolved by resolveStock |
useFormatPrice(options?) |
A price formatter that reads its locale and currency from the site config |
useOrderReadiness(params) |
Debounced determineOrderReadiness |
useCheckoutPersistence(fields) |
Saves checkout fields to sessionStorage and restores them on mount |
usePaginationPrefetch(…) |
Prefetches the next and previous pages on hover |
useModalLifecycle(isOpen, onClose) |
Scroll lock, Escape to close and a hydration gate for modals |
useDebounce(value, delay = 500) |
The value once it has stopped changing for delay ms |
useAugurPersistence(config) |
persistOptions for PersistQueryClientProvider: selective localStorage persistence with size limits |
Stores
- Cart (
useCartStore): prefer the selectorsuseCartHdrUid,useCartLines,useCartQuantityTotal,useCartLineCount,useSetCartHdrUid,useSetCartLinesanduseClearCart, which re-render only on their slice. - Item filters, sorting and paging:
useItemFiltersStore, one store the whole page shares;resetItemsFilters()puts the store'sinitialFiltersStateback, as it stands when reset runs (a site may set it). - A listing's own item filters: wrap the listing in
ItemFiltersProviderand read withuseItemFilters(whole state, or a selector). The provider makes a store when it mounts and drops it when it unmounts, so each listing starts at its defaults and never sees another's filters; give it akey(the category uid, the search) to start fresh when that changes.initialFilterssets the listing's defaults and is read once, when the store is made: a later change takes effect only with a newkey. Outside a provider,useItemFiltersreadsuseItemFiltersStore. - Numeric uids:
ItemFiltersProvider<FilterUid>and read withuseScopedItemFilters<FilterUid>(), which reads only a provider's store and throws outside one (the shared store holds text uids). Make the uids with augur-utilsfilterUidPairsOf(pairs), the site'snumber[][]in one call.
import { ItemFiltersProvider, useItemFilters } from "@simpleapps-com/augur-hooks";
function CategoryPage({ itemCategoryUid }: { itemCategoryUid: number }) {
return (
<ItemFiltersProvider key={itemCategoryUid} initialFilters={{ limit: 24 }}>
<CategoryListing itemCategoryUid={itemCategoryUid} />
</ItemFiltersProvider>
);
}
function CategoryListing({ itemCategoryUid }: { itemCategoryUid: number }) {
const { itemsFilters, setItemsFilters, resetItemsFilters } = useItemFilters();
// …
}createItemFiltersStore(initial?) makes one such store for a site that manages its own lifetime.
Checkout provider
createCheckoutProvider(config) (from /checkout) builds a checkout context and provider. Its optional hooks let a site change the flow without forking it. Define them at module scope or memoize them, so their references stay stable.
| Hook | Signature | Purpose |
|---|---|---|
onShippingAccepted |
(ctx, address, orderCartLines) => void |
After the shipping address is accepted; orderCartLines is the shipping-resolved P21 payload, the raw lines are on the context |
onBeforeSubmit |
(ctx) => boolean | void |
Before submission; return false to cancel |
onAfterSubmit |
(ctx, result) => void |
After a successful submission |
onStepChange |
(ctx, fromStep, toStep) => void |
On each step change |
onValidate |
(ctx) => string | undefined |
Return a message to block submission |
getDefaultPaymentMethod |
() => string |
The first payment method; without it, "credit-card" when config.payments.callbacks is set, else "invoice" |
assembleOrder |
(ctx, state) => { order, error? } |
Builds the payload instead of buildCheckoutPayload |
isOrderReady |
(ctx, params) => boolean | undefined |
Overrides the Process Order gates; undefined keeps the defaults |
To add a site rule to the default gates, call determineOrderReadiness with the override cleared:
import { determineOrderReadiness } from "@simpleapps-com/augur-hooks";
const hooks = {
isOrderReady: (ctx, params) => {
if (!ctx.get("isSampleItems")) return undefined;
return determineOrderReadiness({ ...params, customReadinessCheck: undefined });
},
};Related
- augur-core: the proxies, tiers and keys
- augur-server:
queryActionandcreateServerQueryProxyfor sites whose JWT stays on the server - augur-web:
AugurSiteProviderand the components that use these hooks