@eetech-commerce/cart-react
v0.7.17
Published
React hooks and provider for interacting with the EETech Commerce Cart API.
Downloads
3,016
Readme
@eetech-commerce/cart-react
React hooks and provider for interacting with the EETech Commerce Cart API.
Installation
npm install @eetech-commerce/cart-react
# or
yarn add @eetech-commerce/cart-react
# or
pnpm add @eetech-commerce/cart-react
# or
bun add @eetech-commerce/cart-reactFor payment features (optional):
npm install @stripe/stripe-jsQuick Start
import {
CartProvider,
useCart,
useAddToCart,
} from '@eetech-commerce/cart-react';
function App() {
return (
<CartProvider
tenantSlug="my-store"
cartApiUrl="https://cart.api.com"
>
<Shop />
</CartProvider>
);
}
function Shop() {
const { cart, isLoading } = useCart();
const { addToCart, isPending } = useAddToCart();
if (isLoading) return <div>Loading cart...</div>;
return (
<div>
<h2>Cart ({cart?.items.length ?? 0} items)</h2>
<button
onClick={() => addToCart({ offerId: 'offer-123', quantity: 1 })}
disabled={isPending}
>
Add Item
</button>
</div>
);
}CartProvider Configuration
| Prop | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| tenantSlug | string | Yes | - | Your tenant identifier |
| cartApiUrl | string | Yes | - | Base URL of the cart API |
| storageAdapter | StorageAdapter | No | localStorage | Custom storage implementation |
| queryClient | QueryClient | No | - | Custom TanStack Query client instance |
| getAuthToken | () => Promise<string \| null> | No | - | Async function returning the current auth token (enables authenticated carts) |
Hooks Reference
Cart Hooks
| Hook | Description |
|------|-------------|
| useCart() | Fetch the current cart |
| useCreateCart() | Create a new cart |
| useAddToCart() | Add an item to the cart |
| useUpdateItemQty() | Update item quantity |
| useRemoveItem() | Remove an item from cart |
| useClearCart() | Clear all items from cart |
| useResetCart() | Reset cart (clears session, creates fresh cart) |
Checkout Hooks
| Hook | Description |
|------|-------------|
| useVerifyCart() | Verify cart items before checkout |
| useCreateCheckoutSession() | Create a checkout session |
| useShippingOptions(cartSessionId) | Fetch available shipping options |
| useUpdateShippingSelections() | Update selected shipping options |
| useShippingRegions() | Fetch available shipping countries and states |
Payment Hooks
| Hook | Description |
|------|-------------|
| useStripePromise() | Get the Stripe.js instance |
| useCreateEmbeddedCheckoutSession() | Create an embedded payment session |
| usePaymentSession(sessionId) | Fetch payment session details |
Context Hook
| Hook | Description |
|------|-------------|
| useCartContext() | Access cart context (tenantSlug, cartSessionId, etc.) |
Mutation Callbacks
All mutation hooks support optional callbacks for success and error handling:
const { addToCart } = useAddToCart();
addToCart(
{ offerId: 'offer-123', quantity: 1 },
{
onSuccess: (cart) => {
toast('Added to cart!');
},
onError: (error) => {
toast.error(error.message);
},
}
);Custom Storage Adapter
By default, the cart session ID is stored in localStorage. You can provide a custom storage adapter for different storage mechanisms:
Interface
interface StorageAdapter {
get(key: string): string | null;
set(key: string, value: string): void;
remove(key: string): void;
}Example: Cookie Adapter
import { CartProvider, type StorageAdapter } from '@eetech-commerce/cart-react';
import Cookies from 'js-cookie';
const cookieAdapter: StorageAdapter = {
get: (key) => Cookies.get(key) ?? null,
set: (key, value) => Cookies.set(key, value, { expires: 7 }),
remove: (key) => Cookies.remove(key),
};
function App() {
return (
<CartProvider
tenantSlug="my-store"
cartApiUrl="https://cart.api.com"
storageAdapter={cookieAdapter}
>
<Shop />
</CartProvider>
);
}Resetting the Cart
After a successful payment or when you need a fresh cart, use useResetCart():
import { useResetCart } from '@eetech-commerce/cart-react';
function PaymentSuccessPage() {
const { resetCart } = useResetCart();
useEffect(() => {
resetCart();
}, [resetCart]);
return <div>Payment successful!</div>;
}resetCart() clears the current session, invalidates all cached queries, and creates a new cart.
Using with Existing QueryClient
If your application already uses TanStack Query, you can pass your existing QueryClient to share the cache:
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { CartProvider } from '@eetech-commerce/cart-react';
const queryClient = new QueryClient();
function App() {
return (
<QueryClientProvider client={queryClient}>
<CartProvider
tenantSlug="my-store"
cartApiUrl="https://cart.api.com"
queryClient={queryClient}
>
<Shop />
</CartProvider>
</QueryClientProvider>
);
}Benefits of sharing the QueryClient:
- Unified cache management across your application
- Shared devtools integration
- Consistent query/mutation defaults
Payment Hooks (Stripe)
To use payment features, install @stripe/stripe-js:
npm install @stripe/stripe-jsUsing useStripePromise
The useStripePromise hook automatically fetches your tenant's Stripe publishable key and initializes Stripe.js:
import { useStripePromise } from '@eetech-commerce/cart-react';
import { Elements } from '@stripe/react-stripe-js';
function CheckoutPage() {
const stripePromise = useStripePromise();
if (!stripePromise) {
return <div>Loading payment provider...</div>;
}
return (
<Elements stripe={stripePromise}>
<PaymentForm />
</Elements>
);
}Creating an Embedded Checkout Session
import {
useCreateEmbeddedCheckoutSession,
useCartContext,
} from '@eetech-commerce/cart-react';
function CheckoutButton() {
const { cartSessionId } = useCartContext();
const { createEmbeddedCheckoutSession, isPending, data } =
useCreateEmbeddedCheckoutSession();
const handleCheckout = () => {
createEmbeddedCheckoutSession(
{
cartSessionId: cartSessionId!,
returnUrl: 'https://my-store.com/checkout/complete',
},
{
onSuccess: (session) => {
// Use session.clientSecret with Stripe Embedded Checkout
console.log('Session created:', session.id);
},
onError: (error) => {
console.error('Failed to create session:', error);
},
}
);
};
return (
<button onClick={handleCheckout} disabled={isPending}>
{isPending ? 'Creating session...' : 'Checkout'}
</button>
);
}TypeScript
This package is fully typed. All hooks, providers, and utilities include TypeScript definitions.
Exported Types
import type {
// Provider
CartProviderProps,
CartContextValue,
// Storage
StorageAdapter,
// Mutation callbacks
MutationCallbacks,
// API types
CartResponseDto,
LineItemResponseDto,
CreateCheckoutDto,
VerificationResultDto,
ShippingOptionDto,
ShippingSelectionDto,
CreateEmbeddedPaymentSessionDto,
EmbeddedPaymentSessionResponseDto,
ShippingRegionsResponseDto,
ShippingRegionDto,
} from '@eetech-commerce/cart-react';Advanced: Query Keys
For advanced cache control, query key factories are exported:
import { cartKeys, shippingKeys, paymentKeys } from '@eetech-commerce/cart-react';
// Invalidate all cart queries
queryClient.invalidateQueries({ queryKey: cartKeys.all() });
// Invalidate shipping options
queryClient.invalidateQueries({ queryKey: shippingKeys.all() });License
MIT
