Hooks
Complete guide to hooks in Glood.AI section templates
Template Hooks
Hook Lifecycle Flow
1. Section Initialization Phase
onSectionInit
is called when section is first created- Sets up initial state and variables
- Configures section parameters
- Registers event listeners
2. Data Fetching Phase
getProductDetailsQuery
is called to prepare GraphQL query- Defines required product fields
- Sets up query variables
- Configures custom data requirements
- Sets up filtering parameters
3. Data Processing Phase
postProductFetch
processes raw product data- Filters products if needed
- Adds computed properties
- Transforms data structure
transformProductData
transforms individual product data- Normalizes data format
- Adds custom fields
- Prepares for rendering
4. Rendering Phase
-
afterSectionRendered
is called once section is rendered on the page and ready to be used.Note: This is an optional hook, if you want to perform certain task, you can add your logic in this hook.
-
initSwiper
(if carousel is enabled)- Configures carousel settings
- Sets up navigation
- Initializes responsive behavior
- Sets up pagination
5. Interaction Phase
-
onVariantChange
handles variant selectionNote: This is an optional hook, if you want to perform certain task, you can add your logic in this hook.
-
onSwatchChange
handles swatch interactionsNote: This is an optional hook, if you want to perform certain task, you can add your logic in this hook.
6. Cart Operation Phase
-
beforeAddToCart
validates cart operations- Validates product selection
- Modifies cart payload
- Handles quantity validation
-
afterAddToCart
handles post-cart updatesNote: This is an optional hook, if you want to perform custom logic, you can setup your logic in this hook.
Available Hooks
1. onSectionInit
Purpose:
Primary initialization hook called when a section is first created.
Parameters:
-
args
contains: -
cb
(Callback Function):- Receives the processed recommendation object
- Used to handle initialization completion
- No return value expected
-
gloodUtils
provides:
Function | Description |
---|---|
formatMoney | Formats price values according to store’s money format |
optimizeImage | Optimizes image URLs with specified dimensions and crop settings |
getVariantFromOptions | Finds a variant based on selected options |
findVariantById | Retrieves a variant using its ID |
getSelectedVariant | Gets currently selected variant for a product |
getDefaultVariant | Returns the default/first available variant |
addToCart | Handles adding items to cart with proper validation |
updateCart | Updates existing cart items (quantity, properties) |
getProductUrl | Generates product URL with tracking parameters |
getDiscountedPrice | Calculates discounted price based on rules |
formatDiscount | Formats discount text with proper currency/percentage |
getTranslation | Retrieves translated text with fallback support |
trackEvent | Sends tracking events to analytics |
refreshSection | Re-renders section with updated data |
showNotification | Displays toast/notification messages |
Example:
Use Cases:
- Section configuration
- State initialization
- Event listener setup
- Feature initialization
- Engine configuration
2. getProductDetailsQuery
Purpose:
Builds the GraphQL query for fetching product data.
Parameters:
-
recommendation
contains:section
object with:id
(number): Unique section identifierlayout
(String): Section layout typediscount_config
(Object): Discount settingswidget_message
(String): Custom message template
products
(Array): Currently loaded productstemplate
(Object): Template-specific settings
-
glood
provides:shop
object containing:money_format
(String): Store currency formatlocale
(String): Store language code
product
object with:id
(String): Current product context (format: “gid://shopify/Product/”)handle
(String): Product URL handle
localization
settings for:- Currency formatting
- Language preferences
- Regional settings
Returns:
GraphQL query string containing required product fields
Example:
Use Cases:
- Product data fetching
- Field selection
- Query customization
- Data filtering
- Performance optimization
3. postProductFetch
Description:
Processes raw product data after fetching. Allows for data transformation and enrichment before rendering.
Parameters:
args
(Object):products
(Array): Raw product data arrayrecommendation
(Object): Section configurationtemplate
(Object): Template settings
utils
(Object): Helper functions
Returns:
Array - Processed product data
Example:
Use Cases:
- Price formatting
- Discount calculations
- Image optimization
- Availability checks
- Data enrichment
4. transformProductData
Purpose:
Transforms raw GraphQL product data into template-friendly format.
Parameters:
-
product
(Raw GraphQL data) contains:- Basic information:
id
(String): GraphQL product ID (format: “gid://shopify/Product/”)handle
(String): Product URL handletitle
(String): Product titlevendor
(String): Product vendor
- Images:
featuredImage
(Object): Main product imageimages
(Object): Additional product images
- Pricing:
priceRange
(Object): Min/max pricescompareAtPriceRange
(Object): Original prices
- Variants:
variants
(Object): Product variants datavariantsCount
(Object): Total variants count
- Options:
options
(Array): Product optionsselectedOptions
(Array): Default selections
- Status:
availableForSale
(Boolean): Stock statustags
(Array): Product tags
- Basic information:
-
recommendation
provides:section
settings:- Display configuration
- Pricing rules
- Layout settings
- Tracking configuration
Returns:
Product
object containing:
- Normalized product data
- Formatted prices
- Processed images
- Structured variants
- Computed fields
Example:
Use Cases:
- Tracking setup
- Variant processing
- Label generation
- Price formatting
- Custom field addition
5. initSwiper
Purpose:
Initializes and configures the carousel/slider functionality for sections using Swiper.js.
Parameters:
-
Swiper
(Constructor Class):- Swiper.js constructor
- Used to create carousel instances
- Handles slide functionality
- Manages touch events
- Controls navigation
-
templateSettings
contains:template.settings
with:carousel
(Object): Carousel-specific settingsbreakpoints
(Object): Responsive configuration:small
(Object): Mobile settingsmedium
(Object): Tablet settingslarge
(Object): Desktop settings
- Each breakpoint contains:
screenSize
(Number): Width breakpointcardsPerView
(Number): Visible slidesgutter
(Number): Space between slides
-
container
(HTMLElement):- Root section element
- Contains carousel structure:
- Wrapper element
- Slide elements
- Navigation buttons
- Pagination dots
-
params
contains:recommendation
:section
(Object): Section configurationproducts
(Array): Product data- Layout settings
- Template-specific parameters
-
defaultSettings
contains:- Default Swiper configuration:
- Navigation options
- Pagination settings
- Autoplay configuration
- Effect settings
- Loop behavior
- Default Swiper configuration:
-
utils
provides:merge
: Deep object merging- DOM manipulation helpers
- Event handling utilities
- Error handling functions
Returns:
Swiper
instance if initialization succeedsundefined
if initialization fails
Example:
6. onVariantChange
Purpose:
Handles product variant selection changes and updates the UI.
Parameters:
-
args
contains:variant
information:- Basic details: ID, price, compare price
- Image information with source and alt text
- Availability status and quantity
- Selected options (color, size, etc.)
- Complete
product
data - DOM container element for the product card
-
utils
provides:- Price formatting functions
- Image update utilities
- Price display update functions
- Other UI manipulation helpers
7. onSwatchChange
Purpose:
Handles swatch selection events and updates product display accordingly.
Parameters:
-
args
contains:option
object with:name
(String): Option name (e.g., “Color”, “Size”)value
(String): Selected option valuetype
(String): Swatch type (color/size/material)swatchImage
(String, optional): Custom swatch image URL
product
object containing:variants
(Array): All product variantsoptions
(Array): Available option typesselectedVariant
(Object): Currently selected variantimages
(Array): Product images
container
(HTMLElement): Product card DOM element
-
utils
provides:updateSwatchUI
: Updates swatch selection statefindMatchingVariant
: Finds variant by optionsupdateProductImage
: Updates product imageupdatePriceDisplay
: Updates price display- Event tracking utilities
Returns:
void
8. onCartOperationComplete
Purpose:
Handles post-cart operation tasks and updates UI accordingly.
Parameters:
-
args
contains:operation
(String): Type of operation (‘add’|‘update’|‘remove’)response
object with:cart
(Object): Updated cart stateitems
(Array): Modified cart itemstotal
(Number): New cart totalcount
(Number): Updated item count
section
containing:- Section configuration
- Template settings
- Tracking data
container
(HTMLElement): Section container
-
utils
provides:updateCartUI
: Updates cart displayshowNotification
: Displays notificationsupdateInventory
: Updates stock status- Animation utilities
-
gloodUtils
provides:trackCartEvent
: Analytics trackingformatCartData
: Data formattingupdateShopifyCart
: Cart sync utilities- Store-specific helpers
Returns:
void
9. validateCartOperation
Purpose:
Validates and potentially modifies cart operations before execution.
Parameters:
-
payload
contains:- Array of items being added/modified:
- Product identifier
- Variant identifier
- Quantity
- Additional cart-specific data
- Array of items being added/modified:
-
recommendation
provides:section
configuration- Product data
- Template settings
-
utils
andgloodUtils
:- Validation helpers
- Cart operation utilities
- Format and transformation functions
Returns:
- Modified payload if valid
- Error message if validation fails
- Optional redirect URL
10. onProductDataReceived
Purpose:
Processes raw product data before transformation and rendering.
Parameters:
-
args
contains:products
array with raw product data:id
(number): Product identifiertitle
(String): Product titlehandle
(String): Product URL handlefeaturedImage
(Object): Main product imagevariants
(Array): Raw variant dataoptions
(Array): Product optionstags
(Array): Product tags
section
object with:- Layout configuration
- Discount settings
- Template rules
- Display settings
template
containing:- Breakpoint settings
- Card configuration
- Image dimensions
- Price display rules
-
utils
provides:processImages
: Image optimization utilitiesformatProductData
: Data formatting helpersvalidateProducts
: Data validation functionsenrichProductData
: Data enrichment utilitieshandleErrors
: Error handling functions
Returns:
void
11. loadAjaxCart
Purpose:
Determines when to load the AJAX cart section by checking if the AJAX cart is active.
Parameters:
bodyElem
(HTMLElement):- The document body element
- Provides access to AJAX cart state
Returns:
Boolean
- True if AJAX cart is active and should be loaded
Example:
Use Cases:
- Update recommendations dynamically when products are added to cart
12. unloadAjaxCart
Purpose:
Determines when to unload the AJAX cart section by checking if the AJAX cart is inactive.
Parameters:
bodyElem
(HTMLElement):- The document body element
- Provides access to AJAX cart state
Returns:
Boolean
- True if AJAX cart is inactive and should be unloaded
Example:
Use Cases:
- Control AJAX cart unloading timing
- Clean up cart resources
- Manage AJAX cart states
- Handle cart closure events
Hook Dependencies
Required Utils
formatMoney
: Price formattinggetVariantById
: Variant lookupupdateUrl
: URL manipulationmerge
: Object mergingimageOptimizer
: Image optimization
Global Context
glood
: Store configurationtranslations
: Text stringstemplate
: Template settingssection
: Section configurationutils
: Common utilities
Hook Flow Dependencies
transformProductData
needs data fromgetProductDetailsQuery
afterSectionRendered
needs data fromtransformProductData
- Cart operations need data from
onVariantChange
- Swiper needs container from
afterSectionRendered
Error Handling
Each hook should handle these critical errors:
-
Carousel Initialization Errors
-
Product Data Transformation Errors
-
GraphQL Query Response Errors
These errors require immediate attention as they:
- Prevent sections from rendering correctly
- Break core product functionality
- Impact the shopping experience
- Can cause JavaScript runtime errors
Support
If you need help with creating or customizing section templates, contact our support team at support@glood.ai
Was this page helpful?