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 startNewConversation = 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– Event name (e.g."product_card_clicked","add_to_cart"). - payload
object(optional) – Data merged into the event’sdataobject (e.g. product ID, facets). Sent with every event to Unbxd. - misc
object(optional) – Extra data attached asmiscon the event. Use for non-standard or debug fields.
const { trackAnalytics } = useShoppingAssistant();
// Product card click (e.g. in your ProductComponent)
trackAnalytics({ action: "product_card_clicked" });
trackAnalytics({
action: "product_card_clicked",
payload: { pid: "SKU123", position: 0 }
});
// Add to cart (e.g. in your add-to-cart button handler)
trackAnalytics({
action: "add_to_cart",
payload: { pid: "SKU123", quantity: 1 }
});
// Custom event with misc
trackAnalytics({
action: "custom_event",
payload: { pid: "12345" },
misc: { source: "banner" }
});Behavior:
- No-op when
analyticsis not enabled on the wrapper. - Each event includes: action, userId, visitId, visitType, conversation_id, referrer, url, timestamp, and your payload (merged into
data). misc is sent as a separate field. - Events are sent via beacon to the Unbxd analytics endpoint.
Events overview
| Event Name | Description | Fired by |
|---|---|---|
agent_session_start | New or switched conversation | SDK |
product_card_impression | Products shown in AI response | SDK |
filter_suggestion_applied | Filter suggestion applied | SDK |
image_attached / image_cleared | Visual search image attach/remove | SDK* |
product_card_clicked | User clicks a product card | You (this) |
add_to_cart | User adds product to cart | You (this) |
*When visualAssistant={true}. For You (this) events you must call trackAnalytics in your UI (e.g. product card or add-to-cart handler).
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) - Whether this is a user-initiated action. Defaults totrue. Whenfalse, analytics tracking is skipped (useful for automatic clearing after sending a message).
const { image, clearImage } = useShoppingAssistant();
// Clear image with analytics tracking (default)
const handleRemoveImage = () => {
clearImage(); // or clearImage(true)
};
// Clear image without analytics (e.g., after sending message)
const clearAfterSend = () => {
clearImage(false);
};Behavior:
- Removes the image from state (sets to
null) - Tracks
image_clearedanalytics event ifuserActionistrueand analytics is enabled - Does not track analytics if
userActionisfalse(used internally after sending messages)