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
- Yarn
npm install @haus-storefront-react/hooks
yarn add @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
| Parameter | Type | Required | Description |
|---|---|---|---|
queryOptions | Omit<QueryObserverOptions<Maybe<Channel>, Error, Maybe<Channel>>, 'queryKey'> | No | React Query options (excludes queryKey) |
Returns
| Return Value | Type | Description |
|---|---|---|
data | Maybe<Channel> | The active channel or null |
isLoading | boolean | Loading state flag |
error | string | Error | Error 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
| Parameter | Type | Required | Description |
|---|---|---|---|
queryOptions | Omit<QueryObserverOptions, 'queryKey'> | No | React Query options (excludes queryKey) |
Returns
| Return Value | Type | Description |
|---|---|---|
data | Maybe<Customer> | The authenticated customer or null |
isLoading | boolean | Loading state flag |
error | Error | null | Error 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
| Parameter | Type | Required | Description |
|---|---|---|---|
orderListOptions | OrderListOptions | Yes | Filtering, sorting, and pagination options |
queryOptions | Omit<QueryObserverOptions, 'queryKey'> | No | React 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 Value | Type | Description |
|---|---|---|
data | Maybe<OrderList> | Paginated list of orders or null |
isLoading | boolean | Loading state flag |
error | Error | null | Error 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
| Parameter | Type | Required | Description |
|---|---|---|---|
queryOptions | Omit<QueryObserverOptions<Maybe<Order>, Error, Maybe<T>>, 'queryKey'> | No | React Query options (excludes queryKey) |
Returns
| Return Value | Type | Description |
|---|---|---|
data | Maybe<T> | The active order (cart) or null |
isLoading | boolean | Loading state flag |
error | Error | null | Error 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 Value | Type | Description |
|---|---|---|
addOrderToCart | (order: Order) => Promise<...> | Function to add order items to cart |
isLoading | boolean | Loading state flag |
error | Error | null | Error object if request failed |
isError | boolean | Boolean indicating if mutation failed |
isSuccess | boolean | Boolean indicating if mutation succeeded |
reset | () => void | Function to reset mutation state |
useAdjustOrderLine
Adjusts the quantity of an order line item with debouncing and optimistic updates.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
options | UseAdjustOrderLineOptions | No | Optional configuration |
UseAdjustOrderLineOptions Object
interface UseAdjustOrderLineOptions {
preAdjust?: (orderLineId: string, quantity: number) => Promise<void>
}
Returns
| Return Value | Type | Description |
|---|---|---|
adjustOrderLine | (orderLineId: string, quantity: number) => Promise<Order> | Function to adjust order line quantity |
error | Error | null | Error object if request failed |
isLoading | boolean | Loading state flag |
data | OrderLine[] | undefined | Current order lines from cache |
useAuthentication
Manages user authentication state and operations including login, logout, password reset request, and password reset with token.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
props | UseAuthenticationProps | No | Optional 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 Value | Type | Description |
|---|---|---|
isLoading | boolean | Loading state for any authentication operation |
loginError | Error | null | Error object if login failed |
loginSuccess | boolean | Boolean indicating if login succeeded |
login | (username: string, password: string) => Promise<void> | Function to login |
resetError | Error | null | Error object if password reset request failed |
resetSuccess | boolean | Boolean indicating if password reset request succeeded |
requestPasswordReset | (email: string) => Promise<void> | Function to request password reset |
resetPasswordError | Error | null | Error object if password reset with token failed |
resetPasswordSuccess | boolean | Boolean indicating if password reset with token succeeded |
resetPassword | (token: string, password: string) => Promise<void> | Function to reset password with token |
logoutError | Error | null | Error object if logout failed |
logoutSuccess | boolean | Boolean 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 Value | Type | Description |
|---|---|---|
data | Country[] | undefined | Available countries or undefined while loading |
isLoading | boolean | Loading state flag |
error | Error | null | Error object if request failed |
refetch | () => Promise<void> | Function to manually refetch data |
useCollections
Fetches product collections with optional filtering and pagination.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
options | CollectionListOptions | No | Filtering, 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 Value | Type | Description |
|---|---|---|
data | CollectionList | undefined | Paginated list of collections |
isLoading | boolean | Loading state flag |
error | Error | null | Error object if request failed |
useLazyQuery
Performs queries on demand. The query is disabled by default and only executes when fetch() is called.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
options | UseQueryOptions<TQueryFnData, TError, TData, TQueryKey> | Yes | React Query options (should not include enabled) |
Returns
| Return Value | Type | Description |
|---|---|---|
data | TData | undefined | The query result data |
isLoading | boolean | Loading state flag |
error | TError | null | Error object if request failed |
fetch | () => void | Function to trigger the query |
useOrderByCode
Fetches order details by order code. Only executes when a valid code is provided.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
code | string | Yes | The order code |
queryOptions | Omit<QueryObserverOptions, 'queryKey'> | No | React Query options (excludes queryKey) |
Returns
| Return Value | Type | Description |
|---|---|---|
data | Maybe<T> | The order or null |
isLoading | boolean | Loading state flag |
error | Error | null | Error 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 Value | Type | Description |
|---|---|---|
transitionOrderToState | (state: string) => Promise<Order> | Function to transition order to new state |
nextOrderStates | string[] | undefined | Available next order states |
fetchNextOrderStates | () => void | Function to fetch next order states |
isLoading | boolean | Loading state for any operation |
loadingMap | { orderStates: boolean, transitionOrderToState: boolean } | Loading states for individual operations |
error | Error | null | Error object if request failed |
useProduct
Fetches product details by ID or slug with automatic trailing slash removal.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
iVariables | RequireOnlyOne<{ id: string; slug: string }> | Yes | Either id or slug (exactly one required) |
enabled | boolean | No | Whether the query should execute (default: true) |
Returns
| Return Value | Type | Description |
|---|---|---|
data | T | undefined | The product or undefined |
isLoading | boolean | Loading state flag |
error | Error | null | Error object if request failed |
useRemoveOrderLine
Removes an order line from the cart with optimistic updates.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
options | UseRemoveOrderLineOptions | No | Optional configuration |
UseRemoveOrderLineOptions Object
interface UseRemoveOrderLineOptions {
preRemove?: (lineId: string) => Promise<void>
}
Returns
| Return Value | Type | Description |
|---|---|---|
removeOrderLine | (lineId: string) => Promise<Order> | Function to remove order line |
error | Error | null | Error object if request failed |
isLoading | boolean | Loading state flag |
useSearch
Performs product search with filtering, sorting, and pagination. Automatically removes sort parameter when a search term is provided.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
variables | SearchInput | Yes | Search parameters including term, filters, sorting, and pagination |
queryOptions | Omit<QueryObserverOptions, 'queryKey'> | No | React 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 Value | Type | Description |
|---|---|---|
data | Maybe<T> | Search results or null |
isLoading | boolean | Loading state flag |
error | Error | null | Error 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 Value | Type | Description |
|---|---|---|
setOrderShippingMethod | (shippingMethodId: string | null) => Promise<Maybe<Order>> | Function to set shipping method on order |
refetch | () => void | Function to refetch shipping methods |
shippingMethods | ShippingMethodQuote[] | undefined | Available shipping methods |
error | Error | null | Error object if request failed |
isLoading | boolean | Loading 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 Value | Type | Description |
|---|---|---|
updateOrder | (input: UpdateOrderInput) => Promise<T> | Function to update order |
error | Error | null | Error object if request failed |
loading | boolean | Loading 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
| Parameter | Type | Required | Description |
|---|---|---|---|
options | UseAddItemsToOrderOptions | No | Optional 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 Value | Type | Description |
|---|---|---|
addItemsToOrder | (inputs: AddItemToOrderInput[]) => Promise<...> | Function to add multiple variants to the active cart |
isLoading | boolean | Loading state for the mutation |
error | Error | null | Error object if mutation fails |
isError | boolean | Boolean indicating whether the mutation failed |
isSuccess | boolean | Boolean indicating whether the mutation succeeded |
reset | () => void | Function to reset mutation state |
data | UpdateMultipleOrderItemsResult | undefined | Last successful bulk add result |
Basic Usage
Simple Query Hook
- React
- React Native
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>
)
}
import { View, Text } from 'react-native'
import { useActiveOrder } from '@haus-storefront-react/hooks'
function CartComponent() {
const { data: order, isLoading, error } = useActiveOrder()
if (isLoading) return <Text>Loading cart...</Text>
if (error) return <Text>Error: {error.message}</Text>
if (!order) return <Text>Cart is empty</Text>
return (
<View>
<Text>Cart ({order.totalQuantity} items)</Text>
{order.lines.map((line) => (
<Text key={line.id}>
{line.productVariant.product.name} - {line.quantity}
</Text>
))}
</View>
)
}
Basic Mutation Hook
- React
- React Native
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>
)
}
import { Pressable, Text } from 'react-native'
import { useRemoveOrderLine } from '@haus-storefront-react/hooks'
function RemoveButton({ orderLineId }) {
const { removeOrderLine, isLoading } = useRemoveOrderLine()
const handleRemove = async () => {
await removeOrderLine(orderLineId)
}
return (
<Pressable
onPress={handleRemove}
disabled={isLoading}
>
<Text>{isLoading ? 'Removing...' : 'Remove'}</Text>
</Pressable>
)
}
Advanced Usage
Complex Hook Configuration
- React
- React Native
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>
)
}
import { View, Text, Pressable } from 'react-native'
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)
},
onLoginError: (error) => {
console.error('Login failed:', error)
},
onLogout: async () => {
console.log('Logged out')
},
})
const handleLogin = async (email: string, password: string) => {
try {
await login(email, password)
} catch (e) {
// Error handled by onLoginError callback
}
}
return (
<View>
<Pressable
onPress={() => handleLogin('email', 'password')}
disabled={isLoading}
>
<Text>{isLoading ? 'Loading...' : 'Login'}</Text>
</Pressable>
<Pressable onPress={logout}>
<Text>Logout</Text>
</Pressable>
{loginSuccess && <Text>Successfully logged in!</Text>}
{loginError && <Text>Error: {loginError.message}</Text>}
</View>
)
}
Conditional Rendering Patterns
- React
- React Native
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>
)
}
import { View, Text } from 'react-native'
import { useSearch } from '@haus-storefront-react/hooks'
function SearchComponent({ searchTerm }: { searchTerm: string }) {
const { data, isLoading, error } = useSearch({
term: searchTerm,
take: 20,
})
if (isLoading) {
return <Text>Searching...</Text>
}
if (error) {
return (
<View>
<Text>Error: {error.message}</Text>
</View>
)
}
if (!data || data.totalItems === 0) {
return <Text>No results found</Text>
}
return (
<View>
<Text>Search Results ({data.totalItems})</Text>
{data.items.map((item) => (
<View key={item.productId}>
<Text>{item.productName}</Text>
<Text>{item.description}</Text>
</View>
))}
</View>
)
}
Made with ❤️ by Haus Tech Team