Augur

augur-hooks

React Query hooks, the options proxy, Zustand stores and the checkout provider for Augur data, on web and React Native.

@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-hooks

Peer 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:

  1. With an api: createOptionsProxy(api), so queryFn calls the SDK.
  2. Without one, when a query action is registered (importing @simpleapps-com/augur-server/hooks registers one; registerQueryAction does it by hand): createQueryActionProxy, so queryFn calls the server.
  3. Otherwise: keys only, and each queryFn throws 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.

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
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, so price breaks apply; returns the subtotal and loading state
usePaymentFlow(…) The payment sequence: transaction setup, card info, validation, account query, billing update
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 selectors useCartHdrUid, useCartLines, useCartQuantityTotal, useCartLineCount, useSetCartHdrUid, useSetCartLines and useClearCart, which re-render only on their slice.
  • Item filters, sorting and paging: useItemFiltersStore.

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 });
  },
};
  • augur-core: the proxies, tiers and keys
  • augur-server: queryAction and createServerQueryProxy for sites whose JWT stays on the server
  • augur-web: AugurSiteProvider and the components that use these hooks