Documentation
UnbxdSearchCSRWrapper

UnbxdSearchCSRWrapper

Overview

The UnbxdSearchCSRWrapper is a top-level wrapper component that encapsulates all Client-Side Rendering (CSR) components or hooks used in the application. It acts as the foundational layer for the SDK's functionality, ensuring that any necessary configuration or setup is applied globally. The component accepts a set of props that allow users to customize the behavior of the SDK to suit their specific needs.

Usage

// This is a sample example. 
// Please go through the entire documentation for understanding different usecases and update as per your needs.
import { UnbxdSearchCSRWrapper } from "@unbxd-ui/react-search-hooks";
 
<UnbxdSearchCSRWrapper
	siteKey="TEST_SITEKEY"
	apiKey="TEST_APIKEY"
	defaultValues={{
		pageSize: 12,
		query: "*",
		currentPage: 1,
		view: "GRID",
		sort: "",
	}}
	webUrlConfig={{
		setWebUrl: (newUrl, redirect, replace) => { /* custom logic */ },
		rangeFacets: ["price"],
		categoryFacets: ["categoryPath"],
		externalParams: []
	}}
	apiUrlConfig={{
		category: {...},
		extraParams: () => {
			//This is just a sample code , put your custom code here.
			if (inField) {
				return `category:"${inField}"`;
			} else return null
		}
	}}
	onEvent={({type, message, value, state}) => { /*custom code*/ }}
>
	//Add all your Components here
	<Searchbox />
	<Products />
</UnbxdSearchCSRWrapper>
⚠️
Important:

The UnbxdSearchCSRWrapper component is the core of the SDK, managing all logic and data handling; all other components must be nested within this main component for the search functionality to work seamlessly.

Props

siteKey

string
  • This is the unique Site Key assigned by Unbxd to every site created in the console dashboard.
  • 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.
  • Refer to this section for steps on how to get the API Key for your account.

defaultValues

object
  • This takes in the default values for query, pageSize, view, sort, currentPage.
ConfigDatatypeDefault valueExample value
querystring"""pants"
currentPagenumber15
pageSizenumber1224
viewstring"""GRID"
sortstring"""price asc"
  • Example Usage:
defaultValues = { pageSize: 4 , query: "pants", currentPage: 5, view: "GRID", sort: "price asc" };

webUrlConfig

object
  • Allows you to pass various settings related to the URL to make it more user-friendly. These configurations can include adjustments such as cleaner URL structures, more readable query parameters, or optimized links, enhancing the overall user experience and improving navigation clarity. Below is the usage with each config having default values.
ConfigDatatypeDefault valueDescription
hashModebooleanfalseTurn this flag on if you want the URL to use hash (#) instead of using regular query string delimiter (?).
queryParamSeperatorstring&Seperator used to seperate out each query param in the url.
keySeperatorstring=Seperator used to seperate each param key and value.
orderOfParamsarray[]Add the keys in the order you want them to appear in the url.
queryobject{ addToUrl: true, key: "query" }- addToUrl : Turn to true/false to remove query param from the url.

- key : Pass this to customize the query param key in the url.
imageQueryobject{ addToUrl: true, key: "image" }- addToUrl : Turn to true/false to remove image query param from the url.

- key : Pass this to customize the image query param key in the url.
categoryobject{ addToUrl: true, key: "p" }- addToUrl : Turn to true/false to add/remove category page info from the url.

- key : Whatever passed in here, is used as a key for the browse query param in the url.
sortobject{ addToUrl: true, key: "sort", values: {} }- addToUrl: Turn to true/false to add/remove the sort param from the url.

- key: Whatever passed in here, is used as a key for the sort in the url.

- values: This works as a replacer for the values of sort.
viewobject{ addToUrl: false, key: "view", values: {} }- addToUrl: Turn to true/false to add/remove the view (view) param from the url.

- key: Whatever passed in here, is used as a key for the view in the url.

- values: This works as a replacer for the values of view
pageSizeobject{ addToUrl: true, key: "rows" }- addToUrl: Turn to true/false to add/remove the pagesize (rows) param from the url.

- key: Whatever passed in here, is used as a key for the pagesize in the url.
paginationobject{ addToUrl: true, key: "start", usePageNo: true}- addToUrl - Turn to true/false to add/remove the page (page/start) param from the url.

- key - Whatever passed in here, is used as a key for the page in the url.

- usePageNo: Indicates whether to use page numbers (1,2,3 etc) or indices (0,12,24 etc) in the url.
facetsobject{ addToUrl: true, valuesSeparator: ",", keys: {}, values: {}}- addToUrl: Turn to true/false to add/remove the facets param from the url.

- valuesSeparator: Pass in the character which you would like to use as a seperator between the values for same facet.

- keys: Replace the facet actual names with some custom names in the url .

- values: Replace the facet actual values with some custom values in the url .
externalParamsobjectnullThese are the params other than what unbxd appends, that user wants to add and retain in the url . This can have either of three values : null, [], ["location", "test_param"].

(null: No external params will be considered,
[]: All external params other than unbxd will be considered,
["location"]: Whatever passed in here, for eg: location here will only be retained.)
rangeFacetsarray[]Mention all the range facets names that you would be using.This would help sdk to render facets better.
categoryFacetsarray[]Mention all the category facets names that you would be using.This would help sdk to render facets better.
setWebUrlfunction(newUrl, redirect, replace) => { window.history.pushState({}, "", newUrl); }Function to customize how URL changes are handled. Receives newUrl, redirect, and replace as parameters. See below for details.

- If you are using React Router, you can customize the behavior as follows: const navigate = useNavigate(); const webUrlConfig = { setWebUrl: (newUrl) => { navigate(newUrl); } }
  • Example Usage:
// This is a sample example. 
// Please go through the entire documentation for understanding different usecases and update as per your needs.
webUrlConfig = {
	hashMode: false,
	queryParamSeperator: "&",
	keySeperator: "=",
	orderOfParams: ["sort", "view", "query" , "color_uFilter"],
	query: {
		addToUrl: true,
		key: "query"
	},
	imageQuery: {
		addToUrl: true,
		key: "image"
	},
	category: {
		addToUrl: true,
		key: "browse"
	},
	sort: {
		addToUrl: true,
		key: "sort",
		values: {
			"price asc" : "asc" /* The `price asc` value will appear as `asc` in the url */
		}
	},
	view: {
		addToUrl: false,
		key: "view",
		values: {
			"GRID" : "grid"
		}
	},
	pageSize: {
		addToUrl: true,
		key: "rows"
	},
	pagination: {
		addToUrl: true,
		key: "start",
		usePageNo: true
	},
	facets: {
		addToUrl: true,
		valuesSeparator: ",",
		keys: {},
		values: {},
	},
	externalParams: null,
	rangeFacets: ['price'], /* Mention all your range facets here */
	categoryFacets: [ 'categoryPath' ], /* Mention all your category facets here */
	setWebUrl: (newUrl, redirect, replace) => {
		//This is sample code , use your own code as per the requirement.
		if (replace) {
			window.history.replaceState(null, "", newUrl)
		}
		else window.history.pushState({}, "", newUrl);
	}
};

apiUrlConfig

object
  • This config allows you to pass some cutomization and additional features that are present to make in api url .
ConfigDatatypeDefault valueDescription
searchEndPointstring"https://search.unbxd.io"- searchEndPoint: This is the endpoint that will be used to make the search api call.

categoryobject{browseQueryParam: 'p', page: '', page_type: '' }- browseQueryParam: parameter that will go in the api url . Values can be p or p-id.

- page: Category page path needs to be passed in here.

- page_type: Type of the category page . Value can be boolean.

productsobject{fields: [] }- fields: Pass in the name of fields that needs to be extracted in the search response.

variantsobject{enabled: false, count: 5, attributes: ["title", "v_imageUrl"], mapping: {"image_url": v_imageUrl}}- enabled: Determines whether the variants should be made available for the products or not.

- count: Refers to the number of variants that needs to be shown for a product.

- attributes: List of fields you need for each variant.

- mapping: Field mapping of the catalog attributes to the variant attributes. This is needed to render the variant information correctly.

spellCheckobject{enabled: false}- enabled: This determines whether the spellcheck should be made available or not.
facetMultiSelectbooleantrueAllows a user to select multiple values within a single facet .
uc_paramstring""
extraParamsobject{}Allows to pass some extra params which are needed to be in the search api call. For the values it can be anything including function.
headersobject{}Headers is an object that takes in search api headers and passes it to the Search Api. For the User id and Device type pass it in as Unbxd-User-Id and Unbxd-Device-Type.
  • Example Usage:
// This is a sample example. 
// Please go through the entire documentation for understanding different usecases and update as per your needs.
apiUrlConfig = {
	searchEndPoint: "https://search.unbxd.io",
	category: {
		browseQueryParam: "p",
		page: "",
		page_type: "boolean",
	},
	variants: {
		enabled: true,
		count: 6,
		attributes: ["title", "v_imageUrl"],
		mapping: { image_url: v_imageUrl },
	},
	spellCheck: {
		enabled: true,
	},
	facetMultiSelect: true,
	uc_param: "",
	extraParams: { test: "abc" },
};

onEvent

function
  • A function which helps in capturing events and errors. Users can further run additional pieces of code like error handling or event tracking.
  • In parameters it receives :
    • type: The type of event like BEFORE_API_CALL, AFTER_API_CALL etc.
    • message: The message for the corresponding event.
    • value: The value for the corresponding event.
    • state : Current state values like current page, current selected pagesize, current query etc.
  • Checkout the full list of events below :
Event typeEvent Description
INITIALISEDThis is the event triggered for the first time, once the Wrapper has initialized.
BEFORE_API_CALLThis is the event that is triggered just before the Api call initiates.
AFTER_API_CALLThis is the event that gets triggered once the api call is done.
API_ERRORThis is the event that gets triggered if the API call fails. The error details can be found in the state.error block.
QUERY_UPDATEDEvent that gets triggered when a query has been updated.
AUTOSUGGEST_QUERY_UPDATEDEvent that gets triggered when the autosuggest query has been updated.
IMAGE_SEARCHEvent that gets triggered when the image search has been updated.
SORT_CLICKEDEvent that gets triggered on updating the sort.
BANNER_CLICKEDEvent that gets triggered when there is a click on the banner.
BREADCRUMB_CLICKEDEvent that gets triggered when there is a click on the breadcrumb.
FACET_ADDEDEvent that gets triggered once a facet has been selected.
FACET_REMOVEDEvent that gets triggered once a facet has been de-selected.
FACET_CLEAREDEvent that gets triggered once all facets has been cleared.
PAGE_SIZE_CLICKEDEvent that gets triggered when a pagesize has been selected.
PAGE_CLICKEDEvent that gets triggered when a page number (in pagination) has been selected.
CATEGORY_UPDATEDEvent that gets triggered when the category has been updated.
PRODUCT_VIEW_CLICKEDEvent that gets triggered on selecting a view.
URL_UPDATEDEvent that gets triggered when the URL has been updated.
ERROREvent that gets triggered when an error occurs in some component.
  • Default Value:
const onEvent = ({ type, message, value, state }) => {
	if (message) console.log(`${type}:`, message, value);
	else console.log(type);
};
  • Example Usuage :
//This is sample code , update it according to your requirement.
const onEvent = ({ type, message, value, state }) => {
	// Toast notifications for user feedback
	switch (type) {
		case 'FACET_ADDED':
			showToast(`Filter "${value.name}: ${value.value}" applied`, 'success');
			break;
			
		case 'FACET_CLEARED':
			showToast('All filters cleared', 'info');
			break;
			
		case 'API_ERROR':
			showToast('Search temporarily unavailable. Please try again.', 'error');
			break;
			
		case 'QUERY_UPDATED':
			if (state.response?.numberOfProducts === 0) {
				showToast(`No results found for "${state.query}". Try different keywords.`, 'warning');
			}
			break;
	}
	
	// Update loading states
	if (type === 'BEFORE_API_CALL') {
		document.body.classList.add('search-loading');
	} else if (type === 'AFTER_API_CALL' || type === 'API_ERROR') {
		document.body.classList.remove('search-loading');
	}
};