Managing Cart Items

Plan: Composable Developer

Lesson 18 of 27 · 30 min

Adding Products to an Existing Cart

We’ve seen how to initialize a cart with a list of cart items, but of course your storefront will also need to be able to add new products to a cart on subsequent requests.

The cart.addCartLineItems mutation accepts both a cart ID and a data field. The schema for the data field accepts line item information in the same form as the createCart mutation, so interacting with these two mutations looks largely identical.

mutation AddToCart($cartId: String!, $productId: Int!, $qty: Int!) {
cart {
addCartLineItems(
input: {cartEntityId: $cartId, data: {lineItems: {quantity: $qty, productEntityId: $productId}}}
) {
cart {
entityId
}
}
}
}

Because of the similarity in the input data between these two mutations, it’s usually a simple matter to use conditional logic to determine whether a createCart or addCartLineItems request is needed in response to a user’s “add to cart” interaction.

You’ll practice the proper conditional use of the createCart or addCartLineItems mutations in the next lab exercise.

Updating and Deleting Cart Items

Rounding out our management of items in the cart will be the ability to update or delete items. The mutations for these operations both require two key pieces of information:

  • cartEntityId - To identify which cart is being updated
  • lineItemEntityId - The ID identifying the line item to update/delete. This will correspond with the entityId that can be queried on all line items in a Cart.

Example Update Mutation:

mutation UpdateCartItem($cartId: String!, $lineItemId: String!, $newQty: Int!, $newVariantId: Int) {
cart {
updateCartLineItem(
input: {
cartEntityId: $cartId,
lineItemEntityId: $lineItemId,
data: {
lineItem: {
quantity: $newQty,
variantEntityId: $newVariantId
}
}
}
) {
cart {
...
}
}
}
}

The object expected for lineItem in this mutation is of the same type as that expected in createCart or addCartLineItems(CartLineItemInput), so any details that can be set initially when an item is added can also be updated.

Naturally, the input needed for the delete mutation is simpler.

Example Delete Mutation:

mutation DeleteCartItem($cartId: String!, $lineItemId: String!) {
cart {
deleteCartLineItem(
input: {
cartEntityId: $cartId,
lineItemEntityId: $lineItemId
}
) {
cart {
...
}
}
}
}

Resources