useShoppingAssistant
Overview
The useShoppingAssistant hook is the primary hook for interacting with the Shopping Assistant functionality. It provides access to conversation management, message sending, chat history, and all state related to the AI-powered shopping experience. This hook must be used within a component that is wrapped by the UnbxdShoppingAssistantWrapper.
The useShoppingAssistant hook must be used within a component that is wrapped by UnbxdShoppingAssistantWrapper. Using it outside this context will result in an error.
Usage
import { useShoppingAssistant } from "@unbxd-ui/react-shopping-assistant-hooks";Code Example
const AIAssistant = () => {
const {
startNewConversation,
askAgent,
fetchHistory,
getAllConversations,
updateConversationId,
conversation,
conversationId,
conversationsList,
loading,
initialLoading
} = useShoppingAssistant();
return (
<div>
{/* Your Shopping Assistant UI */}
</div>
);
};Hook API
Return Values
The ID of the current active conversation.
const { conversationId } = useShoppingAssistant();
// Check if conversation is active
if (conversationId) {
console.log("Active conversation:", conversationId);
}Array of chat messages in the current conversation. Each message has a role (user/assistant), message and content.
Conversation Structure:
[
// User message
{
role: "user",
message: "Show me laptops"
},
// Assistant message
{
role: "assistant",
message: "Here are some great laptops for you",
content: {
filters: [...], // Available filters
products: [...] // Product recommendations
}
}
]
Usage:
const { conversation } = useShoppingAssistant();
return (
<div>
{conversation.map((message, index) => (
<div key={index} className={`message ${message.role}`}>
<strong>{message.role}:</strong> {message.message}
{message.content?.products && (
<div>Found {message.content.products.length} products</div>
)}
</div>
))}
</div>
);Array of initial prompt questions/suggestions fetched from the Shopping Assistant API. These are predefined conversation starters that can be displayed to users to help them get started with the shopping assistant.
Questions Structure:
[
"Show me laptops under $1000",
"What are the best running shoes?",
"Find me a gift for my friend"
]Usage:
const { questions, getInitialPrompts, askAgent, conversationId } = useShoppingAssistant();
// Display questions as clickable prompts
return (
<div>
{questions.length > 0 && (
<div>
<h3>Try asking:</h3>
{questions.map((question, index) => (
<button
key={index}
onClick={() => askAgent(question)}
>
{question}
</button>
))}
</div>
)}
</div>
);Behavior:
- Initially empty array (
[]) until api is called - Questions are fetched based on the current
pagetypeandmetadatafrom therequestBodyconfiguration - Each question is a string that can be directly passed to
askAgentwhen clicked - Questions are fetched per conversation and may vary based on the
pagetypeandmetadataprovided in the wrapper'srequestBodyprop
The currently attached image as a base64-encoded string, or null if no image is attached. This is only available when visualAssistant is enabled in the wrapper configuration.
const { image, attachImage, clearImage } = useShoppingAssistant();
// Display attached image preview
{image && (
<div>
<img src={image} alt="Uploaded for visual search" />
<button onClick={() => clearImage()}>Remove</button>
</div>
)}The image value is only available when visualAssistant is enabled.
Array of all conversations for the current user.
const { conversationsList, updateConversationId } = useShoppingAssistant();
// Render conversations list
return (
<div>
{conversationsList.map(conversation => (
<button
key={conversation.id}
onClick={() => updateConversationId(conversation.id)}
>
{conversation.title || `Conversation ${conversation.id}`}
</button>
))}
</div>
);Indicates whether a message is currently being sent/processed.
const { loading, askAgent } = useShoppingAssistant();
return (
<div>
<button
onClick={() => askAgent("Help me find shoes")}
disabled={loading}
>
{loading ? "Sending..." : "Send Message"}
</button>
</div>
);Indicates whether the app is loading (initializing conversation or fetching history).
const { initialLoading, conversation } = useShoppingAssistant();
if (initialLoading) {
return <div>Loading conversation...</div>;
}
return (
<div>
{/* Render chat interface */}
{conversation.map(message => (...))}
</div>
);Initializes a new conversation with the Shopping Assistant API. This function is automatically called when the wrapper loads if no existing conversation is found.
const { startNewConversation } = useShoppingAssistant();
// Start a new conversation
const handleStartNewConversation = async () => {
await startNewConversation();
};Behavior:
- Creates a new conversation ID via API call
- Stores the conversation ID in localStorage or sessionStorage based on wrapper configuration
- Updates the conversation state
Sends a message to the Shopping Assistant AI and receives a response.
Parameters:
- message
string- The user's message to send to the AI - filters
object(optional) - Filters to apply to the search (e.g.{ field: "brand", options: ["Nike"] }for filter suggestions)
const { askAgent } = useShoppingAssistant();
// Basic message
askAgent("Show me laptops under $1000");
// Message with filters
askAgent("Find running shoes", {
field: "brand",
options: ["Nike"]
});Behavior:
- Adds user message to chat history immediately.
- Sets corresponding loading state.
- Sends API request with message and optional filters.
- Adds AI response to chat history when received.
Fetches the chat history for a specific conversation ID.
Parameters:
- conversationId
string- The ID of the conversation to fetch
const { fetchHistory } = useShoppingAssistant();
// Load a specific conversation
const loadConversation = (id) => {
fetchHistory(id);
};Behavior:
- Sets app corresponding loading state.
- Fetches conversation history from API.
- Replaces current chat with fetched history.
Fetches all conversations for the current user.
const { getAllConversations, conversationsList } = useShoppingAssistant();
// Load all user conversations
useEffect(() => {
getAllConversations();
}, []);
// Display conversations list
conversationsList.map(conversation => (
<div key={conversation.id}>{conversation.title}</div>
));Fetches initial prompt questions/suggestions from the Shopping Assistant API for a specific conversation. These questions can be displayed to users as conversation starters.
Parameters:
- conversationId
string- The ID of the conversation to fetch questions for
const { getInitialPrompts, questions, conversationId } = useShoppingAssistant();
// Fetch initial prompts when conversation starts
useEffect(() => {
if (conversationId) {
getInitialPrompts(conversationId);
}
}, [conversationId]);
// Questions will be populated in the questions array after the API call completes
console.log(questions); // Array of question stringsBehavior:
- Makes an API call to fetch questions based on the current
pagetypeandmetadatafrom the wrapper'srequestBodyconfiguration - Updates the
questionsarray in state with the fetched questions - Questions may vary based on the
pagetype(home, search, category, pdp) andmetadataprovided
Note:
- This function must be called manually - it is not automatically called when a conversation starts
- The questions are context-aware and may differ based on the page type and metadata
Updates the current conversation ID in the state and stores it in localStorage/sessionStorage according to the wrapper configurations.
Parameters:
- conversationId
string- The new conversation ID to set
const { updateConversationId } = useShoppingAssistant();
// Switch to a different conversation
const switchConversation = (newId) => {
updateConversationId(newId);
};Sends a custom analytics event to the Unbxd analytics service. Use this for manual events such as product card clicks and add-to-cart. Tracking only runs when UnbxdShoppingAssistantWrapper has analytics={true}; otherwise calls are no-ops.
Parameters (single object):
- action
string– Must be one of the supported action names below. Unknown names log an error and are not sent. - payload
object(optional) – Fields merged into the beacon body’sdataobject (alongside automatic context). Use the shapes in the payload reference table so downstream analytics stay consistent. - misc
object(optional) – Attached at the root of the beacon payload asmiscfor extra vendor-specific fields.
trackAnalytics only submits events whose action is in the supported list. Use exact casing for PRODUCT_IMPRESSIONS.
Beacon envelope
Every submitted event is sent with navigator.sendBeacon as JSON containing:
| Field | Description |
|---|---|
| action | Same string passed to trackAnalytics |
| data | visitId, referrer, visit_type, url, conversation_id , plus every key from payload |
| misc | Your optional misc object, or omitted |
| uid | Visitor identifier |
| t | Timestamp string |
const { trackAnalytics } = useShoppingAssistant();
// Product card click — recommended payload shape (also works with action: "click")
trackAnalytics({
action: "click",
payload: {
pid: "SKU123"
},
});
// Add to cart — include quantity when relevant (also works with action: "cart")
trackAnalytics({
action: "cart",
payload: {
pid: "SKU123",
qty: 1,
},
});
// Optional misc for segmentation or debugging
trackAnalytics({
action: "click",
payload: { pid: "SKU123" },
misc: { placement: "assistant_carousel", rank: 2 },
});Payload reference by action
Automatic events already use these shapes inside the SDK; manual events should follow them where applicable.
| Event Name | When it fires | Trigger | Payload (merged into beacon data via payload) |
|---|---|---|---|
agent_session_start | New conversation from API or loading history for an existing id | Automatic | (none) |
PRODUCT_IMPRESSIONS | Assistant reply includes products | Automatic | pids_list |
filter_suggestion_applied | When filter is applied | Automatic | facets |
image_attached | attachImage completes | Automatic* | (none) |
click | Product tile click in your UI | Manual | pid |
cart | Add-to-cart in your UI | Manual | pid, qty, variantId |
Events overview
| Event Name | Description | Fired by |
|---|---|---|
agent_session_start | New or switched conversation | SDK |
PRODUCT_IMPRESSIONS | Products shown in assistant reply | SDK |
filter_suggestion_applied | Filter passed into askAgent | SDK |
image_attached | Visual search image attached | SDK* |
click | Product card click | Manual |
cart | Add-to-cart | Manual |
*When visualAssistant={true}. image_cleared is not emitted by the current SDK build even though removal hooks exist.
Attaches an image file to be used for visual search. The image is converted to a base64-encoded string and stored in the state. This image will be included in the next message sent via askAgent.
This function is only available when visualAssistant is set to true in the UnbxdShoppingAssistantWrapper configuration. If visualAssistant is false or not set, this function will be undefined.
Parameters:
- image
File- The image file to attach (from file input)
const { attachImage, askAgent } = useShoppingAssistant();
// Handle file input
const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (file) {
attachImage(file);
}
};
// Send message with attached image
const sendVisualSearch = () => {
askAgent("");
// The attached image will automatically be included in the request
};Behavior:
- Converts the image file to base64 format using FileReader
- Stores the base64 string in the state
- Automatically tracks
image_attachedanalytics event (if analytics is enabled) - The image is included in the next
askAgentcall - The image is automatically cleared after sending a message
Removes the currently attached image from the state.
This function is only available when visualAssistant is set to true in the UnbxdShoppingAssistantWrapper configuration. If visualAssistant is false or not set, this function will be undefined.
Parameters:
- userAction
boolean(optional) - Reserved for future analytics around manual clears. Defaults totrue. Internal callers passfalsewhen clearing afteraskAgentso auto-clear paths stay predictable.
const { image, clearImage } = useShoppingAssistant();
const handleRemoveImage = () => {
clearImage(); // or clearImage(true)
};
const clearAfterSend = () => {
clearImage(false);
};Behavior:
- Removes the image from state (sets to
null) image_clearedis not emitted by the current SDK (analytics hook for clear is disabled);userActionis kept for API compatibility