$4.00
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:
Key | Value (type) | Required |
---|---|---|
name | Name of the product to be shown on the Checkout page (string) | Yes in CheckoutSession mode |
description | description to be shown on the Stripe Checkout page (string) | No |
id | A unique identifier for this item (string) | Yes |
price | Price in smallest currency unit (number) | Yes |
currency | ISO currency code (string) | Yes |
image | Image to be shown on the Stripe Checkout page (string) | No |
price_id | Price id provided by Stripe | No |
sku_id | SKU id provided by Stripe (Supports Deprecated API) | No |
sku | A unique identifier for this item (string) | No (Interchangable with id) |
price_data | Optional params for Price API for Serverless integrations | Required for Session id |
product_data | Optional params for Price API for Serverless integrations | Required 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.
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> )}