useProduct
The useProduct hook provides access to the product value passed to <ProductProvider />. It also includes properties for selecting product variants, options, and selling plans.
Usage
import React from "react";
import { ProductProvider, useProduct } from "@airsoko/react";
function ProductPage({ product }) {
return (
<ProductProvider data={product} initialVariantId="product-id">
<UsingProduct />
</ProductProvider>
);
}
function ProductComponent() {
const { product, variants, setSelectedVariant } = useProduct();
const handleVariantClick = (variant) => {
setSelectedVariant(variant);
};
return (
<div>
<h1>{product?.title}</h1>
{variants?.map((variant) => (
<button onClick={() => handleVariantClick(variant)} key={variant?.id}>
{variant?.title}
</button>
))}
</div>
);
}
export default ProductPage;Props
| Name | Type | Required | Description |
|---|---|---|---|
| product | Product | true | The raw product from the Storefront API. |
| variants | ProductVariant[] | true | An array of the variant nodes from the VariantConnection. |
| options | OptionWithValues[] | true | An array of the product's options and values. |
| selectedOptions | SelectedOptions | true | The selected options. |
| variantsConnection | ProductVariantConnection | ||
| selectedVariant | ProductVariant | The selected variant. | |
| selectedSellingPlan | SellingPlanType | The selected selling plan. | |
| selectedSellingPlanAllocation | SellingPlanAllocationType | The selected selling plan allocation. | |
| sellingPlanGroups | (Omit<SellingPlanGroup, "sellingPlans"> & { sellingPlans: SellingPlan[]; })[] | The selling plan groups. | |
| sellingPlanGroupsConnection | SellingPlanGroupConnection |
Functions
| Name | Type | Required | Description |
|---|---|---|---|
| setSelectedVariant | (variant: PartialObjectDeep<ProductVariant, { recurseIntoArrays: true; }>) => void | true | A callback to set the selected variant to the variant passed as an argument. |
| setSelectedOption | (name: string, value: string) => void | true | A callback to set the selected option. |
| setSelectedOptions | (options: SelectedOptions) => void | true | A callback to set multiple selected options at once. |
| setSelectedSellingPlan | (sellingPlan: PartialObjectDeep<SellingPlan, { recurseIntoArrays: true; }>) => void | true | A callback to set the selected selling plan to the one passed as an argument. |
| isOptionInStock | (name: string, value: string) => boolean | true | A callback that returns a boolean indicating if the option is in stock. |