useCart
13 min
The useCart hook returns a series of methods for interacting with the Shopify shopping cart.
import { useCart } from '@chordcommerce/gatsby-theme-performance'
const {
cart,
addPromoCode,
addToCart,
applyGiftCard,
checkout,
loadCart,
modifyQuantity,
removeFromCart,
removeGiftCard,
removePromoCode
} = useCart()cart
Represents the current shopping cart.
Example:
const { cart } = useCart()addPromoCode()
Applies a promo code to the current order.
Example:
const promoCode = '50off'
await addPromoCode(promoCode)addToCart()
Adds an item to the current order.
Example:
const variantId = '123'
const quantity = 1
await addToCart(variantId, quantity)applyGiftCard()
Applies a gift card to the current order.
Example:
const giftCardCode = 'xxxyyyzzz'
await applyGiftCard(giftCardCode)checkout()
Redirects the browser to Shopify checkout.
Example:
await checkout()loadCart()
Reloads the current shopping cart. This is automatically called on every page load and with every other useCart method.
Example:
await loadCart()modifyQuantity()
Updates the quantity of a line item in the current order.
Example:
const lineItemId = '123'
const quantity = 2
await modifyQuantity(lineItemId, quantity)modifyLineItem()
Updates a line item in the current order.
Example:
const lineItemId = '123'
// update line item quantity
await modifyQuantity(lineItemId, {
quantity: 2,
})
// update line item customAttributes
await modifyQuantity(lineItemId, {
customAttributes: [
{
key: 'Est. Shipping Date',
value: 'March 24, 2022',
}
],
})removeFromCart()
Removes a line item from the current order.
Example:
const lineItemId = '123'
await removeFromCart(lineItemId)removeGiftCard()
Removes a gift card from the current order.
Example:
const giftCardCode = 'xxxyyyzzz'
await removeGiftCard(giftCardCode)removePromoCode()
Removes a promo code from the current order.
Example:
const promoCode = '50off'
await removePromoCode(promoCode)