use-shopping-cart

addItem()

addItem()

To add a product to the cart, use useShoppingCart()'s addItem(product) method. It takes in your product object which must be in the following shape:

KeyValue (type)Required
nameName of the product to be shown on the Checkout page (string)Yes in CheckoutSession mode
descriptiondescription to be shown on the Stripe Checkout page (string)No
id A unique identifier for this item (string)Yes
pricePrice in smallest currency unit (number)Yes
currencyISO currency code (string)Yes
imageImage to be shown on the Stripe Checkout page (string)No
price_idPrice id provided by StripeNo
sku_id SKU id provided by Stripe (Supports Deprecated API)No
skuA unique identifier for this item (string)No (Interchangable with id)
price_dataOptional params for Price API for Serverless integrationsRequired for Session id
product_dataOptional params for Price API for Serverless integrationsRequired for Session id
const products = [
{
name: 'Bananas',
description: 'Yummy yellow fruit',
id: 'id_banana001',
price: 400,
currency: 'USD',
image: 'https://my-image.com/banana.jpg'
}
]

HEADS UP

When this library was made, it was done with Stripe's SKU API in mind. SKU is depreceated now in favor of the Price API. This is why sku and id are interchangable. You can use sku if you want, but it's preferred that you use id instead.

You can add an optional quantity param, to add by that number. addItem(product, 10) for example would add by 10.

 Bananas
Bananas

$4.00

{}
export function Product({ product }) {
const { addItem } = useShoppingCart()
/* A helper function that turns the price into a readable format */
const price = formatCurrencyString({
value: product.price,
currency: product.currency,
language: 'en-US'
})
return (
<article
style={{
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
width: '50%'
}}
>
<figure style={{ textAlign: 'center' }}>
<img
style={{ height: 200, width: 250 }}
src={product.image}
alt={` ${product.name}`}
/>
<figcaption>{product.name}</figcaption>
</figure>
<p>{price}</p>
{/* Adds the item to the cart */}
<section
style={{
display: 'flex',
justifyContent: 'space-evenly',
width: '100%'
}}
>
<button
onClick={() => addItem(product)}
aria-label={`Add ${product.name} to your cart`}
style={{ height: 50, width: 100, marginBottom: 30 }}
>
Add to cart
</button>
<button
onClick={() => addItem(product, 10)}
aria-label={`Add 10 ${product.name} to your cart`}
style={{ height: 50, width: 100, marginBottom: 30 }}
>
Add 10 to cart
</button>
</section>
</article>
)
}
Edit this page on GitHub

On this page