The Product Context app is responsible for providing data regarding a certain product to all of its children blocks.
Configuration
- Add the
product-context
app as a dependency in you theme'smanifest.json
file:
"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 setup
in 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 setup
in 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.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 if a selected item is loading or not.
To have the full type definition in your development environment, be sure to run
vtex setup
in your project to install all TypeScript types exported by this app.