---
title: useCart
slug: oms/cH9B-usecart
docTags: 
createdAt: 2022-11-07T21:27:00.000Z
---

:::hint{type="info"}
**This page's documentation only applies to Chord's** [Next.js starter](https://github.com/chordcommerce/nextjs-starter-autonomy) **prior to the release of the&#x20;**[React](docId\:EwXkRz0JhH0zPphIkkcrI)**. The Next.js starter now uses the React SDK and does not use the methods documented on this page. Check out the** [React SDK Reference](https://docs-beta.chord.co/chord-ui/module-react-autonomy) **for complete documentation, and the&#x20;**[React SDK Migration Guide](docId\:qMilHJFPz9WbJYZbe50Ku)**for details on how to upgrade.**
:::

The `useCart` hook returns information about the current shopping cart, and functions for creating and updating the shopping cart.

## Example&#x20;

```javascript
import { useCart } from '~/hooks/actions'

// inside a function component
const { cart, addToCart } = useCart()
```

## Returns

The `useCart` hook returns an object with these properties:

| Property                | Description                                                                                                          |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `cart`                  | An object representing the current shopping cart.                                                                    |
| `addPromoCode`          | A function that applies a promo code to the cart.                                                                    |
| `addReferralIdentifier` | A function that associates a referral identifier with the cart, so the referrer can get credit.                      |
| `addToCart`             | A function that adds a product variant to the cart.                                                                  |
| `checkout`              | A function that prepares the cart for checkout by attaching a `checkoutSessionId` to be passed to Stripe's checkout. |
| `finalizeCheckout`      | A function that loads the finalized order upon checkout completion.                                                  |
| `loadCart`              | A function that loads the current cart based on the current browser session.                                         |
| `modifyCart`            | A function that modifies the current cart.                                                                           |
| `modifyGiftCards`       | A function that applies or removes gift cards from the current cart.                                                 |
| `modifyQuantity`        | A function that modifies the quantity of a line item in the cart.                                                    |
| `removeFromCart`        | A function that removes a line item from the cart.                                                                   |
| `removePromoCode`       | A function that removes an applied promo code from the cart.                                                         |
| `subscribeProduct`      | A function that adds a product variant subscription to the cart.                                                     |
| `crossSell`             | A function that adds an array of line items to the order post checkout.                                              |

## Functions

### addPromoCode&#x20;

The `addPromoCode` function applies a promo code to the current shopping cart.

**Arguments:**

`addPromoCode(promoCode)`

| Argument    | Type   | Description                                           |
| ----------- | ------ | ----------------------------------------------------- |
| `promoCode` | String | The promo code to apply to the current shopping cart. |

**Returns:**

`Promise<void>`: A Promise that resolves when the promo code has been applied to the cart and the `cart` object has been updated to reflect the promo code.

**Example:**

```javascript
import { useCart } from '~/hooks/actions'

const PromoCodeForm = () => {  
  const { cart, addPromoCode } = useCart()
  const onSubmit = async ({ promoCode }) => {  
    try {
      await addPromoCode(promoCode) 
    } catch(error) {
      console.error('Error applying promo code.')
    }  
  }
}
```

### addReferralIdentifier&#x20;

The `addReferralIdentifier` function associates a referral identifier with the cart, so the referrer can get credit. This would likely be called on initial site load, based on a referral identifier in the URL.

**Arguments:**

`addReferralIdentifier(identifier)`

| Argument             | Type   | Description                                                          |
| -------------------- | ------ | -------------------------------------------------------------------- |
| `referralIdentifier` | String | The referral identifier to associate with the current shopping cart. |

**Returns:**

`Promise<void>`: A Promise that resolves when the referral identifier has been associated with the cart.

**Example:**

```javascript
import { useCart } from '~/hooks/actions'

export default () => {  
  const { addReferralIdentifier } = useCart()
  const onSubmit = ({ referralIdentifier }) => {    
    addReferralIdentifier(referralIdentifier)  
  }
}
```

### addToCart&#x20;

The `addToCart` function adds a product variant to the current shopping cart (creating a line item).

**Arguments:**

`addToCart(sku, quantity)`

| Argument   | Type   | Description                                     |
| ---------- | ------ | ----------------------------------------------- |
| `sku`      | String | The product variant SKU to add to the cart.     |
| `quantity` | Number | The quantity of the variant to add to the cart. |

**Returns:**

`Promise<void>`: A Promise that resolves when the new line item has been added to the cart.

**Example:**

```javascript
import { useCart } from '~/hooks/actions'

export default () => {  
  const { addToCart } = useCart()
  const onSubmit = ({ sku, quantity }) => {    
    addToCart(sku, quantity)  
  }
}
```

### checkout&#x20;

The `checkout` function prepares the cart for checkout by attaching a `checkoutSessionId` to be passed to Stripe's checkout. It should be called just before redirecting to Stripe's checkout.

**Arguments:**

None.

**Returns:**

`Promise<Cart>`: A Promise that resolves with the updated cart object when the cart has a `checkoutSessionId` attached.

**Example:**

```javascript
import { useCart } from '~/hooks/actions'
import { loadStripe } from '@stripe/stripe-js'

const stripePromise = loadStripe(process.env.STRIPE_PK_KEY, { 
  stripeAccount: process.env.STRIPE_CONNECTED_ACCOUNT
})

export default () => {  
  const { checkout } = useCart()
  const onSubmit = async () => {    
    const cart = await checkout()    
    const stripe = await stripePromise    
    stripe.redirectToCheckout({ sessionId: cart.checkoutSessionId })  
  }
}
```

### finalizeCheckout&#x20;

The `finalizeCheckout` function should be called when the user is redirected back to the site from Stripe checkout. It retrieves the finalized order for display on the order confirmation page.

This function expects two URL parameters to be present, and uses them to finalize the checkout: `checkout_session_id` and `number`. Stripe will attach these URL parameters when redirecting back to the site.

**Arguments:**

None.

**Returns:**

`Promise<Cart>`: A Promise that resolves with the finalized cart object. This method is the only way to access the finalized cart.

**Example:**

```javascript
import { setState } from 'react'
import { useCart } from '~/hooks/actions'

export default () => {  
  const { finalizeCheckout } = useCart()
  const [cart, setCart] = useState(null)
  
  useEffect(() => {
    finalizeCheckout().then(cart => { setCart(cart) })  
  }, [finalizeCheckout])
}
```

### loadCart&#x20;

The `loadCart` function loads the current cart based on the current browser session and populates the `cart` in Redux. `loadCart` is automatically called on page load.

**Arguments:**

None.

**Returns:**

`Promise<void>`: A Promise that resolves when the `cart` object has been added to Redux.

**Example:**

```javascript
import { useCart } from '~/hooks/actions'

export default () => {  
  const { cart, loadCart } = useCart()

  useEffect(() => {
    loadCart().catch(error => {
      console.error(error.message)
    })
  }, [loadCart])
}
```

### modifyCart&#x20;

The `modifyCart` function modifies the current cart.

**Arguments:**

`modifyCart(options)`

| Argument  | Type   | Description                                                                                                                         |
| --------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------- |
| `options` | Object | An object to send to the Chord OMS [update order endpoint](https://chord.stoplight.io/docs/chord-oms/b3A6MTE3Nzk0Mjk-update-order). |

**Returns:**

`Promise<void>`: A Promise that resolves when the `cart` object has been updated in Redux.

### modifyGiftCards&#x20;

The `modifyGiftCards` function applies or removes gift cards from the current cart.

The `giftCardsDetails` object is returned in the `lineItem` object if the `lineItem` is a gift card. Additionally, newly redeemed gift cards are available in the `user` object for indicating to the user that they have received a gift.

The gift cards can be updated by including the gift card `id` along with any of the following params: `recipientName, recipientEmail, giftMessage, purchaserName, sendEmailAt.`The recipient email is a required field as that will be the account used to redeem the gift cards.

**Arguments:**

`modifyGiftCards(options)`

| Argument  | Type   | Description                                                 |
| --------- | ------ | ----------------------------------------------------------- |
| `options` | Object | An object to send to the Chord OMS bulk gift card endpoint. |

**Returns:**

`Promise<void>`: A Promise that resolves when the `cart` object has been updated in Redux.

Example:

```javascript
modifyGiftCards({
    "giftCardsDetails": [
        {
            "recipientEmail": "test@chord.co",
            "giftMessage": "Hi!",
            "sendEmailAt": "2021-11-15",
            "id": "49"
        },
        {
            "recipientEmail": "admin@chord.co",
            "giftMessage": "",
            "sendEmailAt": "2021-11-16",
            "id": "50"
        }
    ]
})
```

### modifyQuantity&#x20;

The `modifyQuantity` function modifies the quantity of a line item in the current cart.

**Arguments:**

`modifyQuantity(lineItemId, quantity)`

| Argument     | Type   | Description                            |
| ------------ | ------ | -------------------------------------- |
| `lineItemId` | Number | The `id` of the line item to update.   |
| `quantity`   | Number | The desired quantity of the line item. |

**Returns:**

`Promise<void>`: A Promise that resolves when the `cart` object has been updated in Redux.

### removeFromCart&#x20;

The `removeFromCart` function removes a line item from the cart.

**Arguments:**

`removeFromCart(lineItemId)`

| Argument     | Type   | Description                          |
| ------------ | ------ | ------------------------------------ |
| `lineItemId` | Number | The `id` of the line item to update. |

**Returns:**

`Promise<void>`: A Promise that resolves when the `cart` object has been updated in Redux.

### removePromoCode&#x20;

The `removePromoCode` function removes an applied promo code from the cart.

**Arguments**:

`removePromoCode(promoCode)`

| Argument    | Type   | Description                                              |
| ----------- | ------ | -------------------------------------------------------- |
| `promoCode` | String | The promo code to remove from the current shopping cart. |

**Returns:**

`Promise<void>`: A Promise that resolves when the `cart` object has been updated in Redux

### subscribeProduct&#x20;

The `subscribeProduct` function adds a product variant subscription to the cart.

**Arguments:**

Note: `endDate` is optional. The subscription will renew indefinitely if `endDate` is not specified.

`subscribeProduct(options)`

| Argument                  | Type                                   | Description                                                                                                                   |
| ------------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `options.sku`             | String                                 | The product variant SKU for the subscription.                                                                                 |
| `options.quantity`        | Number                                 | The quantity for the subscription.                                                                                            |
| `options.interval`        | Object                                 | The interval for the subscription.                                                                                            |
| `options.interval.length` | Number                                 | The number of units. *Example:* if the subscription should be delivered every three months, this would be `3`.                |
| `options.interval.unit`   | `"day" \| "week" \| "month" \| "year"` | The interval unit. *Example:* if the subscription should be delivered every three months, this would be `month`.              |
| `options.endDate?`        | String                                 | (Optional) A string representing the end date of the subscription. If not provided, the subscription will renew indefinitely. |

**Returns:**

`Promise<void>`: A Promise that resolves when the `cart` object has been updated in Redux.

**Example:**

```javascript
import { useCart } from '~/hooks/actions'

export default () => {  
  const { subscribeProduct } = useCart()
  const onSubmit = ({ sku, quantity, interval, endDate }) => {    
    subscribeProduct({ sku, quantity, interval, endDate })  
  }
}
```

### crossSell&#x20;

The `crossSell` function adds an array of line items to the order post-checkout and charges the credit card again.

**Arguments:**

`crossSell(cart, lineItemsAttributes)`

| Argument              | Type               | Description                                                                         |
| --------------------- | ------------------ | ----------------------------------------------------------------------------------- |
| `cart`                | String             | The `number` of the order (cart)                                                    |
| `lineItemsAttributes` | `Array of Objects` | An array of line item objects that can be both subscription and standard line items |

**Returns:**

`Promise<void>`: A Promise that resolves when the cross-sell has been completed.

**Example:&#x20;**

```javascript
import { useCart } from '~/hooks/actions'

const { crossSell } = useCart()

const cart = "ORDER-1234567"
const lineItems =  
  [
    {
      "sku": "product-1",
      "quantity": 2,
      "subscription_line_items_attributes": [
        {
          "interval_length": 3,
          "interval_units": "month"
        }
      ]
    },
    {
      "sku": "product-2",
      "quantity": 4
    }
  ]

await crossSell(cart, lineItems)
```
