Packages
react
hooks
useProduct

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

NameTypeRequiredDescription
productProducttrueThe raw product from the Storefront API.
variantsProductVariant[]trueAn array of the variant nodes from the VariantConnection.
optionsOptionWithValues[]trueAn array of the product's options and values.
selectedOptionsSelectedOptionstrueThe selected options.
variantsConnectionProductVariantConnection
selectedVariantProductVariantThe selected variant.
selectedSellingPlanSellingPlanTypeThe selected selling plan.
selectedSellingPlanAllocationSellingPlanAllocationTypeThe selected selling plan allocation.
sellingPlanGroups(Omit<SellingPlanGroup, "sellingPlans"> & { sellingPlans: SellingPlan[]; })[]The selling plan groups.
sellingPlanGroupsConnectionSellingPlanGroupConnection

Functions

NameTypeRequiredDescription
setSelectedVariant(variant: PartialObjectDeep<ProductVariant, { recurseIntoArrays: true; }>) => voidtrueA callback to set the selected variant to the variant passed as an argument.
setSelectedOption(name: string, value: string) => voidtrueA callback to set the selected option.
setSelectedOptions(options: SelectedOptions) => voidtrueA callback to set multiple selected options at once.
setSelectedSellingPlan(sellingPlan: PartialObjectDeep<SellingPlan, { recurseIntoArrays: true; }>) => voidtrueA callback to set the selected selling plan to the one passed as an argument.
isOptionInStock(name: string, value: string) => boolean trueA callback that returns a boolean indicating if the option is in stock.