useCart(id?: string)
The useCart()
composable allows for interacting with the Cart data model by:
- loading anonymous and customer carts,
- saving carts,
- restoring saved carts,
- cloning saved carts,
- deleting carts.
Be careful about shared state
You should pass a unique id
as a parameter to avoid state conflicts when using multiple instances of this composable. Every instance with the same id
(or those that lack it) will share the same state, even on different pages. The unique id
is also used to make the loaded cart persistent in a user session.
cart
Main data object populated by the load()
method.
Type
const cart: ComputedProperty<Cart>
References: Cart
loading
Indicates whether any of the composable methods is in progress.
Type
const loading: ComputedProperty<useCartLoading>;
References: UseCartLoading
error
Contains errors thrown by any of the composable methods.
Type
const error: ComputedRef<UseCartError>;
References: UseCartError
load()
Fetches, creates or merges carts and saves the final cart object in the cart property. Under the hood, it sends requests to the getCart or createCart API endpoint.
Type
interface LoadCartProps extends BaseProps {
cartId?: string;
oldCartId?: string;
toMergeCartGuid?: string;
}
async function load(props?: LoadCartProps): Promise<void>;
References: LoadCartProps, BaseProps,
Using a unique id
on useCart()
will make the load()
method persist the loaded cart by storing its code
(for anonymous carts) or guid
(for customer carts) in a dedicated Cookie (opens new window). This ensures cart persistence in a user session.
Example
import { onMounted } from '@nuxtjs/composition-api';
import { useCart } from '@vsf-enterprise/sapcc';
export default {
setup() {
const { load: loadPersistentCart } = useCart('persistent');
const { load: loadTemporaryCart } = useCart();
onMounted(async () => {
await loadPersistentCart(); // will create a `vsf-cart-persistent` cookie
await loadTemporaryCart(); // will create no cookie
});
}
};
Passing the cartId
parameter will seldom be necessary while working with persistent carts. When used for the first time, the load()
method will simply create a new cart. In subsequent calls, it will re-fetch it using the vsf-cart-${id}
cookie.
The cartId
parameter might come in handy if we want to fetch an existing cart but have no intention to store it in a session. It would also allow us to overwrite an existing session cart with a different one.
Example
In this example, we are loading a cart with id = 1
but do not store the id
in browser cookies.
import { onMounted } from '@nuxtjs/composition-api';
import { useCart } from '@vsf-enterprise/sapcc';
export default {
setup() {
const { load: loadCart } = useCart();
onMounted(async () => {
await loadCart({ cartId: '1' });
});
}
};
Example
In this example, we are loading a cart with id = 1
and updating the value of the vsf-cart-persistent
cookie.
import { onMounted } from '@nuxtjs/composition-api';
import { useCart } from '@vsf-enterprise/sapcc';
export default {
setup() {
const { load: loadCart } = useCart('persistent');
onMounted(async () => {
await loadCart({ cartId: '1' });
});
}
};
Since the load()
method is also capable of creating new carts (opens new window), you can use oldCartId
and toMergeCartGuid
parameters to merge anonymous and user carts.
Example
In this example, we are using the oldCartId
parameter to assign an anonymous cart to the user.
import { useCart, useUser } from '@vsf-enterprise/sapcc';
export default {
setup() {
/**
* Script simplified for brevity
*/
const { load, cart } = useCart('persistent');
const { login } = useUser();
const handleLogin = async () => {
await login();
await load({ oldCartId: cart.value.guid });
};
return { handleLogin };
}
};
Example
In this example, we are using both oldCartId
and toMergeCartGuid
parameters to merge an anonymous cart with an existing user cart.
import { useCart, useUser } from '@vsf-enterprise/sapcc';
export default {
setup() {
/**
* Script simplified for brevity
*/
const { load, cart } = useCart('persistent');
const { login } = useUser();
const handleLogin = async () => {
await login();
await load({ oldCartId: cart.value.guid, toMergeCartGuid: '1' });
};
return { handleLogin };
}
};
Remember!
Neither of the oldCartId
and toMergeCartGuid
parameters will work in an anonymous session. Attempting to merge a non-anonymous cart (e.g. with an email assigned to it during checkout) will also throw an error.
If you need full programmatic power over creating or merging carts, you can skip the load()
method and use the createCart API endpoint directly in combination with the set method.
import { onMounted } from '@nuxtjs/composition-api';
import { useCart } from '@vsf-enterprise/sapcc';
import { useVSFContext } from '@vue-storefront/core';
export default {
setup() {
const { $sapcc } = useVSFContext();
const { set: setCart } = useCart('persistent');
onMounted(async () => {
const cart = await $sapcc.api.createCart({ userId: 'anonymous' });
setCart(cart);
});
}
};
Example
In this example, we are explicitly determining the subset of Cart fields we want to retrieve.
import { onMounted } from '@nuxtjs/composition-api';
import { useCart } from '@vsf-enterprise/sapcc';
export default {
setup() {
const { load } = useCart('persistent');
onMounted(async () => {
await load({ fields: 'code,guid,entries(quantity)' });
});
}
};
clear()
Deletes an existing cart and sets the cart property to null
. It calls the deleteCart API endpoint under the hood. If a deleted cart was a session cart, the associated vsf-cart-${id}
cookie is also deleted.
Type
async function clear: () => Promise<void>
Example
In this example, we are composing a method for removing all items from the cart by simply deleting them and replacing them with a new ones.
import { useCart } from '@vsf-enterprise/sapcc';
export default {
setup() {
const { clear, load } = useCart('persistent');
const clearCart = async () => {
await clear();
await load();
};
return { clearCart };
}
};
set()
Sets the cart property manually. When dealing with a session cart, it also updates the associated vsf-cart-${id}
. If called with null
, the associated vsf-cart-${id}
cookie will be removed entirely.
It does not perform any async call under the hood and has no corresponding key either in the loading or error objects.
Type
function set: (newCart: Cart | null) => void;
References: Cart
Example
import { onMounted } from '@nuxtjs/composition-api';
import { useCart } from '@vsf-enterprise/sapcc';
import { useVSFContext } from '@vue-storefront/core';
export default {
setup() {
const { $sapcc } = useVSFContext();
const { set: setCart } = useCart('persistent');
onMounted(async () => {
const cart = await $sapcc.api.createCart({ userId: 'anonymous' });
setCart(cart);
});
}
};
save()
Saves an active user cart and updates the cart property. It calls the saveCart API endpoint under the hood.
Remember!
This method will not work when used during an anonymous session.
Type
interface SaveCartProps extends BaseProps {
name?: string;
description?: string;
}
async function save: (props?: SaveCartProps) => Promise<void>
References: SaveCartProps, BaseProps
Example
This method might come in handy while building a wishlist derived from an anonymous cart in an anonymous session and a saved cart in an authorized session. In the following example, we are first converting an anonymous cart into a user cart using the load method. Second, we are saving the newly-assigned user cart with a proper name
which will identify our new wishlist from now on.
import { useCart } from '@vsf-enterprise/sapcc';
export default {
setup() {
/**
* Script simplified for brevity
*/
const {
cart: wishlist,
load: loadWishlist,
save: saveWishlist
} = useCart('wishlist');
const mergeWishlists = async () => {
await loadWishlist({ oldCartId: wishlist.value.guid });
await saveWishlist({ name: 'wishlist' });
};
return { mergeWishlists };
}
};
Example
In this example, we are saving a cart and selecting response fields.
Use savedCartData in your fields
Instead of simply being a Cart object, the raw SaveCartResult response from SAP Commerce Cloud holds Cart as a nested savedCartData
property. Therefore, it is mandatory to use savedCartData
while selecting the response fields
.
import { onMounted } from '@nuxtjs/composition-api';
import { useCart } from '@vsf-enterprise/sapcc';
export default {
setup() {
const { save: saveCart } = useCart('persistent');
onMounted(async () => {
saveCart({ cartId: '1', fields: 'savedCartData(code,guid)' });
});
}
};
restore()
Restores a saved user cart and updates the cart property. It calls the restoreCart API endpoint under the hood.
Remember!
This method will not work when used during an anonymous session.
Type
async function restore: (props?: BaseProps) => Promise<void>
References: BaseProps
clone()
Clones a saved user cart and returns the newly-created Cart object. It does not alter the original cart property. It calls the cloneCart API endpoint under the hood.
Remember!
This method will not work when used during an anonymous session.
Type
interface CloneCartProps extends BaseProps {
name?: string;
description?: string;
}
async function clone: (props?: CloneCartProps) => Promise<Cart>
References: CloneCartProps, BaseProps