1 min read
Add to Cart Button
Last Updated - Platform 22.0 - SDK 17.0The CartWidget
is a sub-feature of the PoqCatalogue
framework that uses the PoqCartClient
framework.
It is not actually part of the PoqCart
framework but it is related and uses the same repository and service.
Overview
The widget is as View rather than a ViewController and initialises itself with an empty CartWidgetState
.
Views that present one or more products can update the widget using a ProductState
or, preferably, a ProductSelectionState
to persist the product's form selection.
Container Dependencies
Containers can be used to replace most feature dependencies with one line of code.
For the Cart this should be done in the AppModule
on didAddToPlatform
in an organised function such as setUpCart
or setUpDependencies
.
Passing custom data to the Widget
Custom data can be passed to the widget within the CartWidgetState
or ProductState
object used to set it up.
The ProductDetailsViewData
and WishlistItemViewData
both have a cart
property that can be customised via their associated ViewDataMappers.
// Pass your current ProductState directly to forward the product, current selection, and custom data.state.customData = CustomData()CartWidgetState(state)
// You can create the state with only the identifier.// But it is always better to pass the product to avoid additional API calls.CartWidgetState( // Always map the identifier based on the current product selection. id: .init( productId: product.id, listingId: variant.listingId, variantId: state.selection?.selected?.id ), quantity: 1, // Pass your custom data here; used for analytics, custom variant selection, or any customisation. customData: CustomCartWidgetData( isPersonalisable: variant.customData(CustomVariantData.self)?.isPersonalisable ))
Customise the Cart Widget
Customise the CartWidget
via subclassing.
Instead of a builder, the widget has overridable functions for creating its reducers and middleware.
- Create a new file for your widget somewhere like
Sources/Cart/Views
. - Subclass the
CartWidget
and customise.
// It is always good to add comments to describe what customisations you are adding and why.class CustomCartWidget: CartWidget { override func makeAnalyticsMiddleware() { let middleware = super.makeAnalyticsMiddleware() return Middleware { store, action in store.continue(action) switch action { case ServiceAction.CartItem.add(let item): guard let product = store.state?.product, let variant = product.variant(id: item.variantId) else { return Log.error("Missing product or variant") } // Custom tracking goes here.
default: middleware.execute(store: store, action: action) } } }}
- Open your
AppModule
to thedidAddToPlatform
orsetUpCart
function. - Inject your custom widget.
// Inject the widget in your AppModule.Container.shared.views.cartWidget.replace { CustomCartWidget() }