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 🙏

© 2024 – Pkg Stats / Ryan Hefner

shopping-cart-react

v0.1.6

Published

<h1 align="center"> shopping-cart-react </h1> <p align="center"> A tiny React library for managing a shopping cart with tons of features, built with TypeScript. </p>

Downloads

449

Readme

Why?

  • Bundle size
  • 1 dependency
  • 🔥 Persistent carts with local storage
  • 🥞 Works with Next, React, more...
  • 🛠 Built with TypeScript
  • ✅ Fully tested
  • 📦 Works out of the box

Quick Start

Demo

import 'react-app-polyfill/ie11';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { useCart } from '../src';
import { formatCurrencyString } from '../src/utils';

const App = () => {
  const {
    addItemToCart,
    removeItemFromCart,
    clearCart,
    cartItems,
    formattedTotalPrice,
    totalPrice,
    cartCount,
    isEmpty,
    incrementQuantity,
  } = useCart();

  const addApple = () => addItemToCart({ id: '1', name: 'apple', price: 100 });
  const addOrange = () =>
    addItemToCart({ id: '2', name: 'orange', price: 200 });
  const addBanana = () => addItemToCart({ id: '3', name: 'banana', price: 87 });

  return (
    <div>
      <button onClick={addApple}>Add apple</button>
      <button onClick={addOrange}>Add orange</button>
      <button onClick={addBanana}>Add banana</button>
      <button onClick={() => removeItemFromCart('1')}>Remove apple</button>
      <button onClick={clearCart}>Clear Cart</button>
      <button onClick={() => incrementQuantity('3')}>Increment banana</button>
      <div>
        <h2>Cart Items</h2>
        <ul>
          {cartItems.map(item => (
            <li key={item.id}>
              {item.quantity} x {item.name} -
              {formatCurrencyString({ currency: 'USD', value: item.price })}
            </li>
          ))}
        </ul>
        <h3>Total Price: ${totalPrice}</h3>
        <h3>Formatted Total Price: {formattedTotalPrice}</h3>
        <h3>Cart Count: {cartCount}</h3>
        <h3>Is Cart Empty: {isEmpty ? 'Yes' : 'No'}</h3>
      </div>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById('root'));

Install

npm install shopping-cart-react

or

yarn add shopping-cart-react

States and Actions

| Prop | Type | Description | | --------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | cartItems | State | An array of products in the cart, each with attributes like name, id, price, etc. | | cartCount | State | Total quantity of items in the cart. | | isEmpty | State | Boolean value indicating if the cart is empty. | | totalPrice | State | Total price of all items in the cart. | | formattedTotalPrice | State | Formatted total price of items in the cart, according to the selected currency. | | currency | State | The currency used for displaying the cart total. Default is 'USD'. | | setCurrency | Action | Function to set the cart's currency. | | addItemToCart | Action | Function to add a new item to the cart. | | updateQuantity | Action | Function to update the quantity of a specific item in the cart by product ID and quantity. | | incrementQuantity | Action | Function to increase the quantity of a specific item in the cart by one. | | decrementQuantity | Action | Function to decrease the quantity of a specific item in the cart by one. | | removeItemFromCart | Action | Function to remove a specific item from the cart by product ID. | | clearCart | Action | Function to clear all items from the cart, resetting the cart state. | | updateCartMetrics | Action | Function to update cart metrics like total price and item count based on current cart state automatically called after a action that changes cart metrics. |

useCart

The useCart hook exposes all the above States and Actions.

cartItems

Type: State
Description: An array of products currently in the cart. Each product object includes attributes such as name, id, price, etc.

Usage

import { useCart } from 'shopping-cart-react';

const CartItemsExample = () => {
  const { cartItems } = useCart();

  return (
    <div>
      <h2>Cart Items</h2>
      <ul>
        {cartItems.map(item => (
          <li key={item.id}>
            {item.name} - ${item.price / 100}
          </li>
        ))}
      </ul>
    </div>
  );
};

cartCount

Type: State
Description: Total quantity of all items in the cart.

Usage

import { useCart } from 'shopping-cart-react';

const CartCountExample = () => {
  const { cartCount } = useCart();

  return (
    <div>
      <h2>Total Items</h2>
      <p>{cartCount}</p>
    </div>
  );
};

isEmpty

Type: State
Description: A boolean indicating whether the cart is empty.

Usage

import { useCart } from 'shopping-cart-react';

const CartIsEmptyExample = () => {
  const { isEmpty } = useCart();

  return (
    <div>
      {isEmpty ? <p>Your cart is empty.</p> : <p>Your cart has items.</p>}
    </div>
  );
};

totalPrice

Type: State
Description: Total price of all items in the cart in cents (USD).

Usage

import { useCart } from 'shopping-cart-react';

const TotalPriceExample = () => {
  const { totalPrice } = useCart();

  return (
    <div>
      <h2>Total Price</h2>
      <p>{totalPrice}</p>
    </div>
  );
};

formattedTotalPrice

Type: State
Description: Formatted total price of items in the cart, adjusted according to the selected currency.

Usage

import { useCart } from 'shopping-cart-react';

const FormattedTotalPriceExample = () => {
  const { formattedTotalPrice } = useCart();

  return (
    <div>
      <h2>Formatted Total Price</h2>
      <p>${formattedTotalPrice}</p>
    </div>
  );
};

currency

Type: State
Description: The currency used for displaying the cart total. Default is 'USD'.

Usage

import { useCart } from 'shopping-cart-react';

const CurrencyExample = () => {
  const { currency } = useCart();

  return (
    <div>
      <h2>Current Currency</h2>
      <p>{currency}</p>
    </div>
  );
};

setCurrency

Type: Action
Description: Function to set the cart's currency.

Args

  • currency (Required): The currency code to set, e.g., 'USD', 'EUR', etc.

Usage

import { useCart } from 'shopping-cart-react';

const SetCurrencyExample = () => {
  const { setCurrency } = useCart();

  return (
    <div>
      <button onClick={() => setCurrency('EUR')}>Set Currency to EUR</button>
    </div>
  );
};

addItemToCart

Type: Action
Description: Function to add a new item to the cart.

Args

  • item (Required): type Product
export interface Product {
  name: string;
  description?: string;
  id: string;
  price: number;
  image?: string;
  price_id?: string;
  sku_id?: string;
  sku?: string;
  price_data?: any;
  product_data?: any;
  quantity?: number;
}

Usage

import { useCart } from 'shopping-cart-react';

const AddItemToCartExample = () => {
  const { addItemToCart } = useCart();

  const newItem = {
    id: 'example-id',
    name: 'Sample Item',
    price: 2000, // $20.00
  };

  return (
    <div>
      <button onClick={() => addItemToCart(newItem)}>Add Sample Item</button>
    </div>
  );
};

updateQuantity

Type: Action
Description: Function to update the quantity of a specific item in the cart.

Args

  • itemId (Required): The id of the item to update.
  • quantity (Required): The new quantity for the item.

Usage

import { useCart } from 'shopping-cart-react';

const UpdateQuantityExample = () => {
  const { updateQuantity } = useCart();

  return (
    <div>
      <button onClick={() => updateQuantity('example-id', 5)}>
        Set Quantity to 5
      </button>
    </div>
  );
};

incrementQuantity

Type: Action
Description: Function to increase the quantity of a specific item in the cart by one.

Args

  • itemId (Required): The id of the item to increment.

Usage

import { useCart } from 'shopping-cart-react';

const IncrementQuantityExample = () => {
  const { incrementQuantity } = useCart();

  return (
    <div>
      <button onClick={() => incrementQuantity('example-id')}>
        Increase Quantity by 1
      </button>
    </div>
  );
};

decrementQuantity

Type: Action
Description: Function to decrease the quantity of a specific item in the cart by one.

Args

  • itemId (Required): The id of the item to decrement.

Usage

import { useCart } from 'shopping-cart-react';

const DecrementQuantityExample = () => {
  const { decrementQuantity } = useCart();

  return (
    <div>
      <button onClick={() => decrementQuantity('example-id')}>
        Decrease Quantity by 1
      </button>
    </div>
  );
};

removeItemFromCart

Type: Action
Description: Function to remove a specific item from the cart.

Args

  • itemId (Required): The id of the item to remove.

Usage

import { useCart } from 'shopping-cart-react';

const RemoveItemFromCartExample = () => {
  const { removeItemFromCart } = useCart();

  return (
    <div>
      <button onClick={() => removeItemFromCart('example-id')}>
        Remove Item
      </button>
    </div>
  );
};

clearCart

Type: Action
Description: Function to remove all items from the cart and reset the cart state.

Usage

import { useCart } from 'shopping-cart-react';

const ClearCartExample = () => {
  const { clearCart } = useCart();

  return (
    <div>
      <button onClick={() => clearCart()}>Clear Cart</button>
    </div>
  );
};

updateCartMetrics

Type: Action
Description: Function to update cart metrics like total price and item count based on the current cart state.

Usage

import { useCart } from 'shopping-cart-react';

const UpdateCartMetricsExample = () => {
  const { updateCartMetrics } = useCart();

  return (
    <div>
      <button onClick={() => updateCartMetrics()}>Update Cart Metrics</button>
    </div>
  );
};