Shopping Assistant SDK
useShoppingAssistant

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.

⚠️
Important:

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

conversationId

string

The ID of the current active conversation.

const { conversationId } = useShoppingAssistant();
 
// Check if conversation is active
if (conversationId) {
    console.log("Active conversation:", conversationId);
}

conversation

Array

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>
);

questions

Array<string>

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 pagetype and metadata from the requestBody configuration
  • Each question is a string that can be directly passed to askAgent when clicked
  • Questions are fetched per conversation and may vary based on the pagetype and metadata provided in the wrapper's requestBody prop

image

string | null

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>
)}
Note:

The image value is only available when visualAssistant is enabled.


conversationsList

Array

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>
);

loading

boolean

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>
);

initialLoading

boolean

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>
);

startNewConversation

function

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

askAgent

function

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.

fetchHistory

function

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.

getAllConversations

function

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>
));

getInitialPrompts

function

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 strings

Behavior:

  • Makes an API call to fetch questions based on the current pagetype and metadata from the wrapper's requestBody configuration
  • Updates the questions array in state with the fetched questions
  • Questions may vary based on the pagetype (home, search, category, pdp) and metadata provided

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

updateConversationId

function

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);
};

trackAnalytics

function

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’s data object (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 as misc for extra vendor-specific fields.
⚠️
Supported actions only:

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:

FieldDescription
actionSame string passed to trackAnalytics
datavisitId, referrer, visit_type, url, conversation_id , plus every key from payload
miscYour optional misc object, or omitted
uidVisitor identifier
tTimestamp 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 NameWhen it firesTriggerPayload (merged into beacon data via payload)
agent_session_startNew conversation from API or loading history for an existing idAutomatic(none)
PRODUCT_IMPRESSIONSAssistant reply includes productsAutomaticpids_list
filter_suggestion_appliedWhen filter is appliedAutomaticfacets
image_attachedattachImage completesAutomatic*(none)
clickProduct tile click in your UIManualpid
cartAdd-to-cart in your UIManualpid, qty, variantId

Events overview

Event NameDescriptionFired by
agent_session_startNew or switched conversationSDK
PRODUCT_IMPRESSIONSProducts shown in assistant replySDK
filter_suggestion_appliedFilter passed into askAgentSDK
image_attachedVisual search image attachedSDK*
clickProduct card clickManual
cartAdd-to-cartManual

*When visualAssistant={true}. image_cleared is not emitted by the current SDK build even though removal hooks exist.

attachImage

function

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.

⚠️
Availability:

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_attached analytics event (if analytics is enabled)
  • The image is included in the next askAgent call
  • The image is automatically cleared after sending a message

clearImage

function

Removes the currently attached image from the state.

⚠️
Availability:

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 to true. Internal callers pass false when clearing after askAgent so 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_cleared is not emitted by the current SDK (analytics hook for clear is disabled); userAction is kept for API compatibility