The Product Context app is designed to provide essential product data to all child blocks within your store theme.
Configuration
-
Add the
product-contextapp as a dependency to your store theme'smanifest.jsonfile: -
Install the TypeScript types exported by the app by running the following command:
_10vtex setup
Now, you're ready to import components and hooks from the app. Check this example component that displays the product name using data stored in the nearest ProductContext:
_15// Notice that this is TypeScript, and this code should be in a .tsx file_15import React, { FC } from 'react'_15import { useProduct } from 'vtex.product-context'_15_15const MyComponent: FC = () => {_15 const productContextValue = useProduct();_15_15 return (_15 <Fragment>_15 {productContextValue?.product?.productName}_15 </Fragment>_15 )_15}_15_15export default MyComponent
Hooks
useProduct
The useProduct hook allows your app to retrieve data from the nearest ProductContext relative to its caller. Expect an object with the structure below as the return value:
_16interface ProductContextState {_16 selectedItem?: Item | null_16 product: MaybeProduct_16 selectedQuantity: number_16 skuSelector: {_16 selectedImageVariationSKU: string | null_16 isVisible: boolean_16 areAllVariationsSelected: boolean_16 }_16 buyButton: BuyButtonContextState_16 assemblyOptions: {_16 items: Record<GroupId, AssemblyOptionItem[]>_16 inputValues: Record<GroupId, InputValues>_16 areGroupsValid: Record<GroupId, boolean>_16 }_16}
Note that if the hook is called outside a
ProductContextProvider, the return value may beundefinedor an empty object.
useProductDispatch
The useProductDispatch hook provides a dispatch function to manipulate the nearest ProductContext. The function supports the following actions:
SELECT_IMAGE_VARIATION: Sets the value for theskuSelector.selectedImageVariationSKUproperty.SET_QUANTITY: Sets the value for theselectedQuantityproperty.SKU_SELECTOR_SET_VARIATIONS_SELECTED: Sets the value for theskuSelector.areAllVariationsSelectedproperty.SET_BUY_BUTTON_CLICKED: Sets the value for thebuyButton.clickedproperty.SKU_SELECTOR_SET_IS_VISIBLE: Sets the value for theskuSelector.isVisibleproperty.SET_SELECTED_ITEM: Sets the value for theselectedItemproperty.SET_ASSEMBLY_OPTIONS: Sets the value for theassemblyOptionsproperty.SET_PRODUCT: Sets the value for theproductproperty.SET_LOADING_ITEM: Sets the value of whether a selected item is loading.