Create a cart
The Afosto Storefront Client allows you to easily create a cart for your customers' use. This can be automatically or manually handled depending on your preferences. This guide will demonstrate how to create a cart using the client.
Prerequisites
Before proceeding, ensure that you have initialized the Afosto Storefront Client as explained in the "Getting Started" section of the previous documentation. The code snippet below provides a refresher:
1import StorefrontClient from '@afosto/storefront';
2
3const client = StorefrontClient({
4 storefrontToken: 'STOREFRONT_TOKEN',
5});
Remember to replace STOREFRONT_TOKEN
with your actual storefront token.
Auto-Creation of Carts
By default, the client is set to automatically create a cart when adding an item if no cart currently exists. This behavior is controlled by the autoCreateCart
configuration option which is set to true
by default.
When autoCreateCart
is set to true
, the client automatically creates a cart during the addCartItems
operation if no existing cart is found. Here's an example:
1const cart = await client.addCartItems([
2 {
3 sku: 'sku-123',
4 quantity: 1,
5 },
6]);
In the example above, if no cart currently exists, the client will create one before adding the specified items.
Manual Creation of Carts
If you want to manually control when a cart is created, you can set autoCreateCart
to false
during client initialization. Then, use the createCart
function to manually create a cart when needed. Here's how to do it:
1import StorefrontClient from '@afosto/storefront';
2
3const client = StorefrontClient({
4 storefrontToken: 'STOREFRONT_TOKEN',
5 autoCreateCart: false
6});
7
8// Later in your code
9const cart = await client.createCart();
In the example above, the createCart
function is used to manually create a cart. This function returns the newly created cart.
Remember that when autoCreateCart
is set to false
, you must manually create a cart before performing operations that require a cart, such as addCartItems
.
By managing your carts effectively, you can offer a streamlined shopping experience to your users on your Afosto Storefront.