<div
x-data="layersCollection({ collectionHandle: 'shirts' })"
x-init="init()"
@destroy="destroy()"
>
<template x-if="loading">
<p>Loading...</p>
</template>
<template x-if="error">
<p x-text="`Error: ${error.message}`"></p>
</template>
<ul class="product-grid">
<template x-for="product in products" :key="product.id">
<li class="product-card">
<a :href="`/products/${product.handle}`">
<h3 x-text="product.title"></h3>
<span x-text="product.price.formatted"></span>
</a>
</li>
</template>
</ul>
<button @click="loadMore()" x-show="page < totalPages">Load more</button>
</div>
<script type="module">
import { getSDK } from 'https://unpkg.com/@commerce-blocks/sdk@3?module'
window.layersCollection = ({ collectionHandle }) => ({
products: [],
page: 1,
totalPages: 1,
loading: false,
error: null,
_controller: null,
_unsubscribe: null,
init() {
const { data: sdk, error: sdkError } = getSDK()
if (sdkError) {
console.error('SDK not initialized:', sdkError.message)
return
}
this._controller = sdk.collection({ collectionHandle })
this._unsubscribe = this._controller.subscribe(({ data, error, loading }) => {
this.loading = loading
this.error = error
if (data) {
this.products = data.products
this.page = data.page
this.totalPages = data.totalPages
}
})
this._controller.get()
},
loadMore() {
this._controller.get({ pagination: { page: this.page + 1 } })
},
destroy() {
this._unsubscribe?.()
this._controller?.dispose()
},
})
</script>