📢 Use this project, contribute to it or open issues to help evolve it using Store Discussion.
The Product Context app is designed to provide essential product data to all child blocks within your store theme.
-
Add the
product-context
app as a dependency to your store theme'smanifest.json
file:"dependencies": { + "vtex.product-context": "0.x" }
-
Install the TypeScript types exported by the app by running the following command:
vtex 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
:
// 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
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:
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>
}
}
Note that if the hook is called outside a
ProductContextProvider
, the return value may beundefined
or an empty object.
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.selectedImageVariationSKU
property.SET_QUANTITY
: Sets the value for theselectedQuantity
property.SKU_SELECTOR_SET_VARIATIONS_SELECTED
: Sets the value for theskuSelector.areAllVariationsSelected
property.SET_BUY_BUTTON_CLICKED
: Sets the value for thebuyButton.clicked
property.SKU_SELECTOR_SET_IS_VISIBLE
: Sets the value for theskuSelector.isVisible
property.SET_SELECTED_ITEM
: Sets the value for theselectedItem
property.SET_ASSEMBLY_OPTIONS
: Sets the value for theassemblyOptions
property.SET_PRODUCT
: Sets the value for theproduct
property.SET_LOADING_ITEM
: Sets the value of whether a selected item is loading.
Thanks goes to these wonderful people:
Sahan Jayawardana 💻 |
This project follows the all-contributors specification. Contributions of any kind welcome!