Shopping Assistant SDK
UnbxdShoppingAssistantWrapper

UnbxdShoppingAssistantWrapper

Overview

The UnbxdShoppingAssistantWrapper is a foundational wrapper component that provides context and state management for all Shopping Assistant functionality. It acts as the core provider that enables AI-powered conversational shopping experiences by managing chat state, conversation history, API communication, and user interactions. All Shopping Assistant components and hooks must be wrapped within this component to function properly.

⚠️
Important:

The UnbxdShoppingAssistantWrapper component is essential for Shopping Assistant functionality, managing conversation state, API communication, and chat history; all Shopping Assistant components must be nested within this wrapper to access the shopping assistant context and features.

Usage

// This is a sample example. 
// Please go through the entire documentation for understanding different use cases and update as per your needs.
import { UnbxdShoppingAssistantWrapper } from "@unbxd-ui/react-shopping-assistant-hooks";
 
<UnbxdShoppingAssistantWrapper
	siteKey="YOUR_SITE_KEY"
	apiKey="YOUR_API_KEY"
	convStorageType="LOCALSTORAGE"
	analytics={true}
	headers={{
		uid: "user123",
		deviceType: "desktop"
	}}
	extraParams={{
		customParam: "value"
	}}
>
	<ChatComponent />
</UnbxdShoppingAssistantWrapper>

Props

siteKey

string
  • This is the unique Site Key assigned by Unbxd to every site created in the console dashboard.
  • Required for authenticating API requests to the Shopping Assistant service.
  • Refer to this section for steps on how to get the Site Key for your account.

apiKey

string
  • This is the unique API Key assigned to every site created in the console dashboard.
  • Used for authenticating Shopping Assistant API calls.
  • Refer to this section for steps on how to get the API Key for your account.

convStorageType

'LOCALSTORAGE' | 'SESSIONSTORAGE'
  • Determines where the conversation ID should be stored for persistence across browser sessions.
  • LOCALSTORAGE: The conversation id will be stored in Local Storage and the conversation persists across browser sessions until manually cleared .
  • SESSIONSTORAGE: The conversation id will be stored in Session Storage and the conversation only persists for the current browser session .
  • "": When left empty the conversation id will not be stored anywhere.
  • Default value:: ``

convStorageName

string
  • Specifies the key name used to store the conversation ID in localStorage or sessionStorage.
  • This allows you to customize the storage key name to avoid conflicts with other conversation ids stored in the browser's storage.
  • Only used when convStorageType is set to 'LOCALSTORAGE' or 'SESSIONSTORAGE'.
  • Default value:: "conversationId"
//Example implementation
<UnbxdShoppingAssistantWrapper
	siteKey="YOUR_SITE_KEY"
	apiKey="YOUR_API_KEY"
	convStorageType="LOCALSTORAGE"
	convStorageName="myAppConversationId"
>
	<ChatComponent />
</UnbxdShoppingAssistantWrapper>

Use Cases:

  • Multiple Instances: Use different storage names when you have multiple Shopping Assistant instances on the same domain
Note:

If convStorageType is set to an empty string (""), the convStorageName value is ignored as no storage operations are performed.

fetchAllConversations

boolean
  • Tells if all conversations need to be fetched or not.
  • Default value:: false

apiEndpoint

string
  • Specifies the endpoint to be used for the API call.

requestBody

object | function
  • Specifies additional data to be included in the Shopping Assistant API request body.
  • Can be an object (static or with dynamic function values) or a function that receives the request type and returns the body for that call.
  • Commonly used to send pagetype and metadata for API calls.
  • Default value:: {}

Object form: Use a plain object; values can be functions that are executed per request.

// Example: static object with dynamic metadata
<UnbxdShoppingAssistantWrapper
	siteKey="YOUR_SITE_KEY"
	apiKey="YOUR_API_KEY"
	...
	requestBody={{
		pagetype: "home",
		metadata: ()=>{
			return {
				uniqueId: "2312892"
			}
		}
	}}
>
	<ChatComponent />
</UnbxdShoppingAssistantWrapper>

Function form: Pass a function that receives the request type and returns the body. Use this when the payload must differ by API call.

  • Request types: "INITIAL_CONVERSATION" (start conversation), "CHAT" (send message), "QUESTIONS" (fetch initial prompts).
// Example: function that returns different body per request type
<UnbxdShoppingAssistantWrapper
	...
	requestBody={(type) => {
		if (type === "INITIAL_CONVERSATION") return { pagetype: "home", metadata: {} };
		if (type === "CHAT") return { pagetype: "search", metadata: { query: getCurrentQuery() } };
		if (type === "QUESTIONS") return { pagetype: "category", metadata: { category_id: getCategoryId() } };
		return {};
	}}
>
	<ChatComponent />
</UnbxdShoppingAssistantWrapper>

Common pagetype and metadata values:

1. {"pagetype":"home","metadata":{}}  
2. {"pagetype":"search","metadata":{"query":"Hi"}}  
3. {"pagetype":"category","metadata":{"category_id":"mens_running"}}  
4. {"pagetype":"pdp","metadata":{"uniqueId":"12345"}}

headers

object
  • Custom headers to be sent with Shopping Assistant API requests.
  • Can include both static values and dynamic functions that return values.
  • Default value:: {}
//Example implementation
headers={{
	deviceType: "desktop",
	sessionId: () => getSessionId(), // Dynamic function
	customHeader: "value"
}}

extraParams

object
  • Additional parameters to be included in Shopping Assistant API requests.
  • Supports both static values and dynamic functions.
  • Useful for passing custom filters, metadata, or configuration.
  • Passing uid is mandatory in the extraParams for the sdk to work properly.
  • Default value:: {}
//Example implementation
extraParams={{
	uid: "user123",
	category: "electronics",
	brand: "apple",
	priceRange: () => getCurrentPriceFilter(),
	customParam: "value"
}}

analytics

boolean
  • Enables or disables analytics tracking for Shopping Assistant interactions. Analytics is true by default .
  • When true:
    • Automatic initialization: The sdk sets user/visit identifiers (userId, visitId, visitType, referrer) in cookies and session storage.
    • Automatic events: Session starts, product impressions, and filter applications are tracked without any extra code.
    • Manual events: Use the trackAnalytics function from useShoppingAssistant to fire product_card_clicked, add_to_cart, and any custom events.
  • Each event sent to Unbxd includes user context (userId, visitId, visitType), conversation ID, referrer, current URL, and your optional payload/misc data. Events are sent via beacon to the Unbxd analytics endpoint.
  • Default value:: true
// Enable analytics to track Shopping Assistant interactions
<UnbxdShoppingAssistantWrapper
	siteKey="YOUR_SITE_KEY"
	apiKey="YOUR_API_KEY"
	analytics={true}
>
	<ChatComponent />
</UnbxdShoppingAssistantWrapper>

Analytics events

Event NameWhen it firesTrigger
agent_session_startA new conversation starts or user switches conversationAutomatic
product_card_impressionProducts are shown in an AI responseAutomatic
filter_suggestion_appliedA filter suggestion is applied (e.g. from AI response)Automatic
image_attachedUser attaches an image (visual search)Automatic*
image_clearedUser removes an attached imageAutomatic*
product_card_clickedUser clicks a product cardManual
add_to_cartUser adds a product to cartManual
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:

Events marked Automatic are fired by the SDK. For Manual events you must call trackAnalytics from useShoppingAssistant (e.g. in your product card or add-to-cart button handlers). See the useShoppingAssistant – trackAnalytics section for usage.

visualAssistant

boolean
  • Enables or disables visual assistant functionality in the Shopping Assistant.
  • When true, enables image upload capabilities for visual product search, allowing users to upload images to find similar products.
  • When enabled, the useShoppingAssistant hook exposes attachImage and clearImage functions for managing image uploads.
  • Default value:: false
//Example implementation
<UnbxdShoppingAssistantWrapper
	siteKey="YOUR_SITE_KEY"
	apiKey="YOUR_API_KEY"
	visualAssistant={true}
>
	<ChatComponent />
</UnbxdShoppingAssistantWrapper>

When visualAssistant is enabled:

  • The attachImage function becomes available in the useShoppingAssistant hook
  • The clearImage function becomes available in the useShoppingAssistant hook
  • Users can upload images that will be included in their messages to the AI assistant
  • Images are automatically converted to base64 format and sent with the next askAgent call
  • Analytics events image_attached and image_cleared are automatically tracked (if analytics is enabled)

Usage Example:

import { useShoppingAssistant } from "@unbxd-ui/react-shopping-assistant-hooks";
 
const VisualSearchComponent = () => {
    const { attachImage, clearImage, image, askAgent } = useShoppingAssistant();
 
    const handleImageUpload = (event) => {
        const file = event.target.files?.[0];
        if (file) {
            attachImage(file);
        }
    };
 
    const handleSendWithImage = () => {
        // Image will be automatically included in the request
        askAgent("Find similar products");
    };
 
    return (
        <div>
            {image && (
                <div>
                    <img src={image} alt="Uploaded" />
                    <button onClick={() => clearImage()}>Remove Image</button>
                </div>
            )}
            <input 
                type="file" 
                accept="image/*" 
                onChange={handleImageUpload} 
            />
            <button onClick={handleSendWithImage}>Search with Image</button>
        </div>
    );
};
Note:

The attachImage and clearImage functions are only available when visualAssistant is set to true in the wrapper configuration. Attempting to use these functions when visualAssistant is false will result in undefined values.

onEvent

function
  • A function which helps in capturing events and errors during shopping assistant interactions. Users can further run additional pieces of code like error handling, event tracking, or analytics.

  • In parameters it receives:

    • type: The type of event like CONVERSATION_STARTED, MESSAGE_SENT, AGENT_RESPONSE_RECEIVED etc.
    • message: The message for the corresponding event.
    • value: The value for the corresponding event (conversation ID, message content, etc.).
    • state: Current state values like conversation history, loading states, conversation ID etc.
  • Checkout the full list of events below:

Event typeEvent Description
CONVERSATION_STARTEDThis event is triggered when a new conversation is initiated.
CONVERSATION_RESETThis event is triggered when a conversation is reset (reserved for future use).
MESSAGE_SENTEvent triggered when a user sends a message to the shopping assistant.
AGENT_RESPONSE_RECEIVEDEvent triggered when the AI agent responds with a message.
CONVERSATION_LOADEDEvent triggered when conversation history is loaded from storage.
CONVERSATIONS_FETCHEDEvent triggered when all conversations are retrieved for the user.
INITIAL_PROMPTS_LOADEDEvent triggered when initial conversation prompts are loaded.
UPDATE_CONVERSATION_IDEvent triggered when the conversation ID is updated.
UPDATE_INITIAL_LOADINGEvent triggered when initial loading state changes.
LOADING_STARTEDEvent triggered when any loading operation begins.
LOADING_FINISHEDEvent triggered when any loading operation completes.
ERROREvent triggered when an error occurs in any shopping assistant operation.
  • Default Value:
const onEvent = ({ type, message, value, state }) => {
	if (message) console.log(`${type}:`, message);
	else console.log(type);
};
  • Example Usage:
// This is sample code, update it according to your requirement.
const onEvent = ({ type, message, value, state }) => {
	switch (type) {
		case 'CONVERSATION_STARTED':
			console.log('New conversation started:', value);
			// Track conversation start in analytics
			analytics.track('conversation_started', { conversationId: value });
			break;
 
		case 'MESSAGE_SENT':
			console.log('User message sent:', value);
			// Track user engagement
			analytics.track('user_message_sent', { message: value });
			break;
 
		case 'AGENT_RESPONSE_RECEIVED':
			console.log('AI response received:', value);
			// Track AI interaction
			analytics.track('ai_response_received', { response: value });
			break;
 
		case 'ERROR':
			console.error('Shopping assistant error:', value);
			// Send error to monitoring service
			errorTracking.captureException(value);
			break;
 
		case 'LOADING_STARTED':
			// Show loading indicator
			setLoadingState(true);
			break;
 
		case 'LOADING_FINISHED':
			// Hide loading indicator
			setLoadingState(false);
			break;
 
		default:
			console.log(`Event: ${type}`, { message, value });
	}
};