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,
        resetChat,
        fetchHistory,
        getAllConversations,
        updateConversationId,
        chat,
        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

function

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, chat } = useShoppingAssistant();
 
if (initialLoading) {
    return <div>Loading conversation...</div>;
}
 
return (
    <div>
        {/* Render chat interface */}
        {chat.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 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

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) - Additional filters to apply to the search
  • metadata object (optional) - Additional metadata to include with the request
const { askAgent } = useShoppingAssistant();
 
// Basic message
askAgent("Show me laptops under $1000");
 
// Message with filters
askAgent("Find running shoes", {
    brand: "nike",
    size: "10"
});
 
// Message with metadata
askAgent("What's trending?", null, {
    source: "homepage",
    timestamp: Date.now()
});

Behavior:

  • Adds user message to chat history immediately.
  • Sets corresponding loading state.
  • Sends API request with message, filters, and metadata.
  • 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

Tracks custom analytics events to the Unbxd analytics service. This function automatically sends events with user context, visit information, and conversation details. Analytics tracking only works when the analytics prop is enabled in the wrapper configuration.

Parameters:

  • action string - The name of the analytics event (e.g., "product_card_clicked", "filter_applied")
  • payload object (optional) - Additional data to include in the analytics event
  • misc object (optional) - Miscellaneous data to attach to the event
const { trackAnalytics } = useShoppingAssistant();
 
// Track a simple event
trackAnalytics({ action: "product_card_clicked" });
 
// Track an event with additional data
trackAnalytics({ 
    action: "filter_suggestion_applied",
    payload: {
        facets: { brand: ["Nike", "Adidas"] }
    }
});
 
// Track an event with misc data
trackAnalytics({ 
    action: "custom_event",
    payload: { pid: "12345" },
    misc: { source: "banner" }
});

Behavior:

  • Only tracks events when analytics is enabled in the wrapper configuration
  • Automatically includes user context (userId, visitId, visitType)
  • Includes conversation context (conversation_id, referrer, url)
  • Generates a unique timestamp for each event

Common Analytics Events:

Event NameEvent Description
agent_session_startFired when a new conversation starts
filter_suggestion_appliedFired when a filter suggestion is applied
product_card_impressionFired when products are displayed
product_card_clickedFired when a user clicks on a product card (manual trigger)
add_to_cartFired when a user adds a product to cart (manual trigger)
Important:

By default, the Shopping Assistant automatically fires three analytics events: agent_session_start, product_card_impression, and filter_suggestion_applied. The events product_card_clicked and add_to_cart must be manually fired on the user's end using the trackAnalytics function.

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) - Whether this is a user-initiated action. Defaults to true. When false, 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_cleared analytics event if userAction is true and analytics is enabled
  • Does not track analytics if userAction is false (used internally after sending messages)