@nosto/search-js
    Preparing search index...

    Function useSwatches

    • Preact hook for managing swatch options and selection.

      This hook aggregates SKU data by specified fields (e.g., "color", "size"), generates swatch options, and manages the selection state for those options.

      • Use matchedSkus to:
      • Display preview data like images or prices from partial selections.
      • Enable actions like "Add to Cart" when exactly one matching SKU remains.

      Parameters

      • skus: SearchProductSku[] = []
      • fields: string[] = []

      Returns {
          matchedSkus: SearchProductSku[];
          swatches: SwatchField[];
          toggleOption: (field: string, value: string) => void;
      }

      import { useSwatches } from '@nosto/search-js/preact/hooks'

      export default () => {
      const { swatches, toggleOption, matchedSkus } = useSwatches(skus, ["color", "size"])

      const canAddToCart = matchedSkus.length === 1
      const previewImage = matchedSkus[0]?.imageUrl || "/fallback.jpg"

      return (
      <div>
      <img src={previewImage} alt="Product preview" width={200} />

      {swatches.map(({ field, options }) => (
      <div key={field}>
      {options.map(({ value, unavailable, selected }) => (
      <button
      key={value}
      disabled={unavailable}
      onClick={() => toggleOption(field, value)}
      style={{
      margin: "4px",
      padding: "8px 12px",
      background: selected ? "#0070f3" : "#eee",
      color: selected ? "#fff" : "#000",
      opacity: unavailable ? 0.3 : 1
      }}
      >
      {value}
      </button>
      ))}
      </div>
      ))}

      <button disabled={!canAddToCart}>
      Add to Cart
      </button>
      </div>
      )
      }