π This is a typescript, hook using shopping cart lib, persistent by default, that I'm hopeful will help a few people out.
$ npm install react-hook-cart
Check out the Demo.
This is a Provider Component to wrapper around your entire app(or a section of it) in order to create context for the cart.
storage
can take other methods to store cart, default uses localStorage.
import { CartProvider } from "react-hook-cart";
<CartProvider>
<App />
</CartProvider>
Function to expose cart functionality
import { useCart } from "react-hook-cart";
const { items, isEmpty, totalCost, addItem, removeItem, clearCart } = useCart();
items
in an Item
array
import { useCart } from "react-hook-cart";
const { items } = useCart();
const ShowCart = () => {
return (
<div>
<ul>
{items.map((item) => (
<li>{item.id}</li>
))}
</ul>
</div>
);
};
Adds the item to the items array
-
Item
is an object{id: string, price: number}
, it can have additional properties{id: string, price: number, name:"example"}
-
quantity
is a number, but optional. Default value is 1
const { addItem } = useCart();
return (
<button onClick={()=>addItem({id: "Br73s", price: 5}, 2)}>Add 2 bread for 5 USD each</button>
);
Removes all of the items with that id.
id
is a string
const { removeItem } = useCart();
return (
<button onClick={()=>removeItem("Br73s")}>Remove items</button>
);
updateItem
updates the item with the updates object.
-
id
is a string -
updates
is an object
const { updateItem } = useCart();
return (
<button onClick={()=>updateItem("Br73s", { size: "Large" })}>Make it a large bread!</button>
);
updateItemQuantity
changes the quantity of an item to the exact quantity given.
-
id
is a string -
quantity
is a number
const { updateItemQuantity } = useCart();
return (
<button onClick={()=>updateItemQuantity("Br73s", 5)}>Set item amount to 5</button>
);
clearCart()
empties the cart, and resets the state.
const { clearCart } = useCart();
return (
<button onClick={()=>clearCart()}>Empty the cart!</button>
);
A quick and easy way to check if the cart is empty.
isEmpty
is a boolean.
const { isEmpty } = useCart();
return (
<p>The cart is {isEmpty ? "empty" : "not empty"}</p>
);
Get item with that id.
id
is a string
const { getItem } = useCart();
const item = getItem("Br73s")}>
Quickly check if an item is in the cart.
-
id
is a string -
returns a boolean
const { inCart } = useCart();
const itemWasInCart = inCart("Br73s")}>
The total amount of items in the cart.
totalItems
is a number
const { totalItems } = useCart();
return (
<p>There are {totalItems} in the cart</p>
);
The total amount of unique items in the cart.
totalUniqueItems
is a number
const { totalUniqueItems } = useCart();
return (
<p>There are {totalUniqueItems} in the cart</p>
);
The total cost of all the items in the cart.
totalCost
is a number
const { totalCost } = useCart();
return (
<p>The total cost of the cart is: {totalCost}</p>
);