The Product Context app is responsible for providing data regarding a certain product to all of its children blocks.
Configuration
- Add the
product-contextapp as a dependency in you theme'smanifest.jsonfile:
"dependencies": {
+ "vtex.product-context": "0.x"
}
Now, you can import any of the exported components and hooks from the app. Here's an example of a component that render's the name of the product whose data is stored in the nearest ProductContext:
// Notice that this is TypeScript, and this code should be in a .tsx file
import React, { FC } from 'react'
import { useProduct } from 'vtex.product-context'
const MyComponent: FC = () => {
const productContextValue = useProduct()
return (
<Fragment>
{productContextValue?.product?.productName}
</Fragment>
)
}
export default MyComponent
Be sure to run
vtex setupin your project to install the correct TypeScript types exported by this app.
Hooks
useProduct
This is the most useful export from this app. The useProduct hook can be used to read the data from the nearest ProductContext relative to its caller.
The productContextValue variable from the example above has the following type definition:
interface ProductContextState {
selectedItem?: Item | null
product: MaybeProduct
selectedQuantity: number
skuSelector: {
selectedImageVariationSKU: string | null
isVisible: boolean
areAllVariationsSelected: boolean
}
buyButton: BuyButtonContextState
assemblyOptions: {
items: Record<GroupId, AssemblyOptionItem[]>
inputValues: Record<GroupId, InputValues>
areGroupsValid: Record<GroupId, boolean>
}
}
You should expect an object that looks like that as the return value of useProduct. Be aware that, if the hook is called outside of a ProductContextProvider, the return value could be undefined or an empty object.
To have the full type definition in your development environment, be sure to run
vtex setupin your project to install all TypeScript types exported by this app.
useProductDispatch
This hooks returns a dispatch function which you can use to manipulate the nearest ProductContext.
The function is capable of performing 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 if a selected item is loading or not.
To have the full type definition in your development environment, be sure to run
vtex setupin your project to install all TypeScript types exported by this app.