> For the complete documentation index, see [llms.txt](https://docs.chord.co/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.chord.co/chord-oms/developer-tools/next-js/sdk-reference/usecart.md).

# useCart

{% hint style="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** [React](/chord-oms/developer-tools/react.md)**. 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** [React SDK Migration Guide](/chord-oms/developer-tools/next-js/guides/react-sdk-migration-guide.md)**for details on how to upgrade.**
{% endhint %}

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

## Example

```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

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

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

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

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

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

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

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

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

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

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

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

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

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:**

```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)
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.chord.co/chord-oms/developer-tools/next-js/sdk-reference/usecart.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
