useRecommendation
Use recommendation query hook to request and retrieve data for recommendation widgets.
Generic response
RequestResponse
{
rfkId,
actions: {
onNavigationNext: ({ index: number }) => void,
onNavigationPrev: ({ index: number }) => void,
onProductClick: ({ sku: string }) => void
},
context: {
// Here we destructure the context variables that we would like to obtain.
},
queryResult: {
isLoading, // The query has no data and is currently fetching
isError,// The query encountered an error
isSuccess, // The query was successful and data is available
isFetching, // In any state, if the query is fetching at any time (including background refetching) isFetching will be true.
data: {
{ content: { product: { value: products = [] } } }
} = {},
},
}Import
RequestResponse
import { useRecommendation } from '@sitecore-discover/react';Example
RequestResponse
import React from 'react';
import { WidgetDataType, WidgetsProvider, useRecommendation, widget } from '@sitecore-discover/react';
const MyApp = () => {
return (
<WidgetsProvider
env='<environment>'
customerKey='<customer key>'
apiKey='<API key provided in CEC>'
useToken
>
<MyRecommendationWidget productsToDisplay={4} />
</WidgetsProvider>
)};
const MyRecommendationComponent = ({ productsToDisplay = 6 }) => {
const {
actions: { onProductClick },
queryResult: { isLoading, isFetching, data: { content: { product: { value: products = [] } = {} } = {} } = {} },
} = useRecommendation((query) => {
query.getRequest().setNumberProducts(productsToDisplay);
});
const ready = !isLoading && !isFetching;
if (!ready || (ready && products.length === 0)) {
return '';
}
return (
<div>
{products.map((p, index) => (
<div key={`product-${index}`}>
<h3><a href="#" onClick={() => onProductClick({ sku: p.sku || '' })}>{p.name}</a></h3>
<img src={p.image_url} />
{p.final_price && <span>${p.final_price}</span>}
</div>
))}
</div>
);
};
// Register the widget
const MyRecommendationWidget = widget(Recommendation, WidgetDataType.RECOMMENDATION);Note
Convert a UI component into a widget component before adding it to pages.
To convert a component into a widget component, pass the UI component to the widget or setWidget function.