-
Notifications
You must be signed in to change notification settings - Fork 214
Expand file tree
/
Copy pathuse-controlled-variations.js
More file actions
58 lines (50 loc) · 1.93 KB
/
use-controlled-variations.js
File metadata and controls
58 lines (50 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
* Copyright (c) 2021, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import {useState, useEffect, useCallback} from 'react'
/**
* Custom hook for managing controlled variation state in modals.
* Provides React state-based variation management (instead of URL parameters).
*
* Features:
* - Manages variation selection state
* - Auto-selects single-value variation attributes
* - Provides callback for handling variation changes
*
* @param {Object} product - The product object with variationAttributes
* @returns {Object} - { controlledVariationValues, handleVariationChange }
*/
export const useControlledVariations = (product) => {
const [controlledVariationValues, setControlledVariationValues] = useState({})
// Auto-select variation attributes with only one value
useEffect(() => {
if (!product?.variationAttributes) return
const autoSelections = {}
product.variationAttributes.forEach((attr) => {
// Only auto-select if there's exactly one value and it's not already selected
if (attr.values?.length === 1 && !controlledVariationValues[attr.id]) {
autoSelections[attr.id] = attr.values[0].value
}
})
if (Object.keys(autoSelections).length > 0) {
setControlledVariationValues((prev) => ({
...prev,
...autoSelections
}))
}
}, [product?.variationAttributes, controlledVariationValues])
// Handle variation changes in controlled mode
const handleVariationChange = useCallback((attributeId, value) => {
setControlledVariationValues((prev) => ({
...prev,
[attributeId]: value
}))
}, [])
return {
controlledVariationValues,
handleVariationChange
}
}