npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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-react

For payment features (optional):

npm install @stripe/stripe-js

Quick 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-js

Using 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