Skip to main content

Hooks

Collection of React hooks for e-commerce functionality.

Purpose

This library provides a comprehensive set of React hooks for managing e-commerce operations including cart management, product data, user authentication, orders, and search functionality. All hooks are designed to work seamlessly with the core SDK and provide consistent data fetching patterns using React Query for caching, background refetching, and optimistic updates.

Features

  • Cart Management: Add, adjust, and remove items from the shopping cart with optimistic updates
  • Authentication: Login, logout, and password reset functionality with event bus integration
  • Product Data: Fetch products by ID or slug with automatic caching
  • Search: Product search with filtering, sorting, and pagination support
  • Orders: View active orders, customer order history, and order details by code
  • Collections: Fetch product collections with filtering options
  • Shipping: Get eligible shipping methods and update order shipping
  • Channel Management: Manage active channel selection for multi-channel stores
  • React Query Integration: Built on React Query for automatic caching, background refetching, and request deduplication

Installation

npm install @haus-storefront-react/hooks

Note: This is not a public package. Contact the Haus Tech Team for access.

API Reference

useActiveChannel

Fetches the current active channel. Includes a function to set the channel token.

Parameters

ParameterTypeRequiredDescription
queryOptionsOmit<QueryObserverOptions<Maybe<Channel>, Error, Maybe<Channel>>, 'queryKey'>NoReact Query options (excludes queryKey)

Returns

Return ValueTypeDescription
dataMaybe<Channel>The active channel or null
isLoadingbooleanLoading state flag
errorstring | ErrorError object or string if channel token is invalid
setChannelToken(token: string, asDefaultToken?: boolean) => Promise<void>Function to set the channel token

useActiveCustomer

Fetches the current authenticated customer with automatic refetching on window focus, mount, and reconnect.

Parameters

ParameterTypeRequiredDescription
queryOptionsOmit<QueryObserverOptions, 'queryKey'>NoReact Query options (excludes queryKey)

Returns

Return ValueTypeDescription
dataMaybe<Customer>The authenticated customer or null
isLoadingbooleanLoading state flag
errorError | nullError object if request failed
refetch() => Promise<void>Function to manually refetch data

useActiveCustomerOrders

Fetches orders for the current authenticated customer with filtering and pagination support.

Parameters

ParameterTypeRequiredDescription
orderListOptionsOrderListOptionsYesFiltering, sorting, and pagination options
queryOptionsOmit<QueryObserverOptions, 'queryKey'>NoReact Query options (excludes queryKey)

OrderListOptions Object

interface OrderListOptions {
filter?: Maybe<OrderFilterParameter>
filterOperator?: Maybe<LogicalOperator>
skip?: Maybe<number>
sort?: Maybe<OrderSortParameter>
take?: Maybe<number>
}

Returns

Return ValueTypeDescription
dataMaybe<OrderList>Paginated list of orders or null
isLoadingbooleanLoading state flag
errorError | nullError object if request failed
refetch() => Promise<void>Function to manually refetch data

useActiveOrder

Fetches the current active order (cart) with automatic refetching on window focus and mount.

Parameters

ParameterTypeRequiredDescription
queryOptionsOmit<QueryObserverOptions<Maybe<Order>, Error, Maybe<T>>, 'queryKey'>NoReact Query options (excludes queryKey)

Returns

Return ValueTypeDescription
dataMaybe<T>The active order (cart) or null
isLoadingbooleanLoading state flag
errorError | nullError object if request failed
refetch() => Promise<void>Function to manually refetch data

useAddOrderToCart

Adds all items from an order to the cart. Handles multiple items and returns success/error information.

Parameters

None

Returns

Return ValueTypeDescription
addOrderToCart(order: Order) => Promise<...>Function to add order items to cart
isLoadingbooleanLoading state flag
errorError | nullError object if request failed
isErrorbooleanBoolean indicating if mutation failed
isSuccessbooleanBoolean indicating if mutation succeeded
reset() => voidFunction to reset mutation state

useAdjustOrderLine

Adjusts the quantity of an order line item with debouncing and optimistic updates.

Parameters

ParameterTypeRequiredDescription
optionsUseAdjustOrderLineOptionsNoOptional configuration

UseAdjustOrderLineOptions Object

interface UseAdjustOrderLineOptions {
preAdjust?: (orderLineId: string, quantity: number) => Promise<void>
}

Returns

Return ValueTypeDescription
adjustOrderLine(orderLineId: string, quantity: number) => Promise<Order>Function to adjust order line quantity
errorError | nullError object if request failed
isLoadingbooleanLoading state flag
dataOrderLine[] | undefinedCurrent order lines from cache

useAuthentication

Manages user authentication state and operations including login, logout, password reset request, and password reset with token.

Parameters

ParameterTypeRequiredDescription
propsUseAuthenticationPropsNoOptional callbacks for authentication events

UseAuthenticationProps Object

interface UseAuthenticationProps {
onLogin?: (username: string) => Promise<void> | void
onLoginError?: (error: Error) => void
onReset?: () => void
onResetError?: (error: Error) => void
onPasswordReset?: (email: string) => Promise<void> | void
onPasswordResetError?: (error: Error) => void
onLogout?: () => Promise<void> | void
onLogoutError?: (error: Error) => void
}

Returns

Return ValueTypeDescription
isLoadingbooleanLoading state for any authentication operation
loginErrorError | nullError object if login failed
loginSuccessbooleanBoolean indicating if login succeeded
login(username: string, password: string) => Promise<void>Function to login
resetErrorError | nullError object if password reset request failed
resetSuccessbooleanBoolean indicating if password reset request succeeded
requestPasswordReset(email: string) => Promise<void>Function to request password reset
resetPasswordErrorError | nullError object if password reset with token failed
resetPasswordSuccessbooleanBoolean indicating if password reset with token succeeded
resetPassword(token: string, password: string) => Promise<void>Function to reset password with token
logoutErrorError | nullError object if logout failed
logoutSuccessbooleanBoolean indicating if logout succeeded
logout() => Promise<void>Function to logout

useAvailableCountries

Fetches the list of available countries for the store. Returns a standard React Query result for the available countries list.

Parameters

None

Returns

Return ValueTypeDescription
dataCountry[] | undefinedAvailable countries or undefined while loading
isLoadingbooleanLoading state flag
errorError | nullError object if request failed
refetch() => Promise<void>Function to manually refetch data

useCollections

Fetches product collections with optional filtering and pagination.

Parameters

ParameterTypeRequiredDescription
optionsCollectionListOptionsNoFiltering, sorting, and pagination options

CollectionListOptions Object

interface CollectionListOptions {
topLevelOnly?: Maybe<boolean>
skip?: Maybe<number>
take?: Maybe<number>
sort?: Maybe<CollectionSortParameter>
filter?: Maybe<CollectionFilterParameter>
filterOperator?: Maybe<LogicalOperator>
}

Returns

Return ValueTypeDescription
dataCollectionList | undefinedPaginated list of collections
isLoadingbooleanLoading state flag
errorError | nullError object if request failed

useLazyQuery

Performs queries on demand. The query is disabled by default and only executes when fetch() is called.

Parameters

ParameterTypeRequiredDescription
optionsUseQueryOptions<TQueryFnData, TError, TData, TQueryKey>YesReact Query options (should not include enabled)

Returns

Return ValueTypeDescription
dataTData | undefinedThe query result data
isLoadingbooleanLoading state flag
errorTError | nullError object if request failed
fetch() => voidFunction to trigger the query

useOrderByCode

Fetches order details by order code. Only executes when a valid code is provided.

Parameters

ParameterTypeRequiredDescription
codestringYesThe order code
queryOptionsOmit<QueryObserverOptions, 'queryKey'>NoReact Query options (excludes queryKey)

Returns

Return ValueTypeDescription
dataMaybe<T>The order or null
isLoadingbooleanLoading state flag
errorError | nullError object if request failed
refetch() => Promise<void>Function to manually refetch data

useOrderStates

Fetches available next order states and provides a function to transition orders to a new state.

Parameters

None

Returns

Return ValueTypeDescription
transitionOrderToState(state: string) => Promise<Order>Function to transition order to new state
nextOrderStatesstring[] | undefinedAvailable next order states
fetchNextOrderStates() => voidFunction to fetch next order states
isLoadingbooleanLoading state for any operation
loadingMap{ orderStates: boolean, transitionOrderToState: boolean }Loading states for individual operations
errorError | nullError object if request failed

useProduct

Fetches product details by ID or slug with automatic trailing slash removal.

Parameters

ParameterTypeRequiredDescription
iVariablesRequireOnlyOne<{ id: string; slug: string }>YesEither id or slug (exactly one required)
enabledbooleanNoWhether the query should execute (default: true)

Returns

Return ValueTypeDescription
dataT | undefinedThe product or undefined
isLoadingbooleanLoading state flag
errorError | nullError object if request failed

useRemoveOrderLine

Removes an order line from the cart with optimistic updates.

Parameters

ParameterTypeRequiredDescription
optionsUseRemoveOrderLineOptionsNoOptional configuration

UseRemoveOrderLineOptions Object

interface UseRemoveOrderLineOptions {
preRemove?: (lineId: string) => Promise<void>
}

Returns

Return ValueTypeDescription
removeOrderLine(lineId: string) => Promise<Order>Function to remove order line
errorError | nullError object if request failed
isLoadingbooleanLoading state flag

useSearch

Performs product search with filtering, sorting, and pagination. Automatically removes sort parameter when a search term is provided.

Parameters

ParameterTypeRequiredDescription
variablesSearchInputYesSearch parameters including term, filters, sorting, and pagination
queryOptionsOmit<QueryObserverOptions, 'queryKey'>NoReact Query options (excludes queryKey)

SearchInput Object

interface SearchInput {
term?: Maybe<string>
collectionId?: Maybe<string>
collectionSlug?: Maybe<string>
facetValueIds?: Maybe<Array<string>>
facetValueOperator?: Maybe<LogicalOperator>
facetValueFilters?: Maybe<Array<FacetValueFilterInput>>
groupByProduct?: Maybe<boolean>
inStock?: Maybe<boolean>
sort?: Maybe<SearchResultSortParameter>
take?: Maybe<number>
skip?: Maybe<number>
}

Returns

Return ValueTypeDescription
dataMaybe<T>Search results or null
isLoadingbooleanLoading state flag
errorError | nullError object if request failed
refetch() => Promise<void>Function to manually refetch data

useShippingMethods

Fetches eligible shipping methods and provides a function to set the shipping method on an order.

Parameters

None

Returns

Return ValueTypeDescription
setOrderShippingMethod(shippingMethodId: string | null) => Promise<Maybe<Order>>Function to set shipping method on order
refetch() => voidFunction to refetch shipping methods
shippingMethodsShippingMethodQuote[] | undefinedAvailable shipping methods
errorError | nullError object if request failed
isLoadingbooleanLoading state for any operation
loadingMap{ shippingMethods: boolean, setOrderShippingMethod: boolean }Loading states for individual operations

useUpdateOrder

Updates an order with billing/shipping addresses, shipping method, payment method, customer info, custom fields, or coupon codes.

Parameters

None

Returns

Return ValueTypeDescription
updateOrder(input: UpdateOrderInput) => Promise<T>Function to update order
errorError | nullError object if request failed
loadingbooleanLoading state flag

UpdateOrderInput Object

interface UpdateOrderInput {
billingAddress?: Maybe<CreateAddressInput>
shippingAddress?: Maybe<CreateAddressInput>
shippingMethodId?: Maybe<string>
paymentMethodCode?: Maybe<string>
customer?: Maybe<CreateCustomerInput>
customFields?: Record<string, unknown>
couponCode?: {
code: Maybe<string>
remove?: boolean
}
}

useAddItemsToOrder

Adds multiple items to the active order in a single operation and exposes success/error callbacks for bulk add workflows.

Parameters

ParameterTypeRequiredDescription
optionsUseAddItemsToOrderOptionsNoOptional lifecycle callbacks for pre-add validation and mutation handling

UseAddItemsToOrderOptions Object

interface UseAddItemsToOrderOptions {
callbacks?: {
preAdd?: (inputs: AddItemToOrderInput[]) => Promise<void> | void
}
onSuccess?: (result: UpdateMultipleOrderItemsResult) => void
onError?: (error: Error) => void
}

Returns

Return ValueTypeDescription
addItemsToOrder(inputs: AddItemToOrderInput[]) => Promise<...>Function to add multiple variants to the active cart
isLoadingbooleanLoading state for the mutation
errorError | nullError object if mutation fails
isErrorbooleanBoolean indicating whether the mutation failed
isSuccessbooleanBoolean indicating whether the mutation succeeded
reset() => voidFunction to reset mutation state
dataUpdateMultipleOrderItemsResult | undefinedLast successful bulk add result

Basic Usage

Simple Query Hook

import { useActiveOrder } from '@haus-storefront-react/hooks'

function CartComponent() {
const { data: order, isLoading, error } = useActiveOrder()

if (isLoading) return <div>Loading cart...</div>
if (error) return <div>Error: {error.message}</div>
if (!order) return <div>Cart is empty</div>

return (
<div>
<h2>Cart ({order.totalQuantity} items)</h2>
{order.lines.map((line) => (
<div key={line.id}>
{line.productVariant.product.name} - {line.quantity}
</div>
))}
</div>
)
}

Basic Mutation Hook

import { useRemoveOrderLine } from '@haus-storefront-react/hooks'

function RemoveButton({ orderLineId }) {
const { removeOrderLine, isLoading } = useRemoveOrderLine()

const handleRemove = async () => {
await removeOrderLine(orderLineId)
}

return (
<button onClick={handleRemove} disabled={isLoading}>
{isLoading ? 'Removing...' : 'Remove'}
</button>
)
}

Advanced Usage

Complex Hook Configuration

import { useAuthentication } from '@haus-storefront-react/hooks'

function AdvancedAuth() {
const {
isLoading,
login,
logout,
loginError,
loginSuccess,
requestPasswordReset,
resetPassword,
} = useAuthentication({
onLogin: async (username) => {
console.log('Logged in as:', username)
// Navigate to dashboard
},
onLoginError: (error) => {
console.error('Login failed:', error)
// Show error toast
},
onLogout: async () => {
console.log('Logged out')
// Navigate to home
},
})

const handleLogin = async (email: string, password: string) => {
try {
await login(email, password)
} catch (e) {
// Error handled by onLoginError callback
}
}

return (
<div>
<button
onClick={() => handleLogin('email', 'password')}
disabled={isLoading}
>
{isLoading ? 'Loading...' : 'Login'}
</button>
<button onClick={logout}>Logout</button>
{loginSuccess && <div>Successfully logged in!</div>}
{loginError && <div>Error: {loginError.message}</div>}
</div>
)
}

Conditional Rendering Patterns

import { useSearch } from '@haus-storefront-react/hooks'

function SearchComponent({ searchTerm }: { searchTerm: string }) {
const { data, isLoading, error } = useSearch({
term: searchTerm,
take: 20,
})

if (isLoading) {
return <div>Searching...</div>
}

if (error) {
return (
<div>
<p>Error: {error.message}</p>
</div>
)
}

if (!data || data.totalItems === 0) {
return <div>No results found</div>
}

return (
<div>
<h2>Search Results ({data.totalItems})</h2>
{data.items.map((item) => (
<div key={item.productId}>
<h3>{item.productName}</h3>
<p>{item.description}</p>
</div>
))}
</div>
)
}

Made with ❤️ by Haus Tech Team