All Projects → notrab → react-use-cart

notrab / react-use-cart

Licence: Apache-2.0 license
React hook library for managing cart state

Programming Languages

typescript
32286 projects
HTML
75241 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to react-use-cart

ng-shopping-cart
🛒 An Angular component library to create shopping carts
Stars: ✭ 46 (-84.51%)
Mutual labels:  shopping-cart, cart, cart-items
Gogrocery
Its an eCommerce app inspired from Amazon , big Basket , grofers ,grocery app , Etc
Stars: ✭ 62 (-79.12%)
Mutual labels:  shopping-cart, cart
Co Cart
🛒 CoCart is a flexible, open-source solution to enabling the shopping cart via the REST API for WooCommerce.
Stars: ✭ 198 (-33.33%)
Mutual labels:  shopping-cart, cart
Laravel Ecommerce
AvoRed an Open Source Laravel Shopping Cart
Stars: ✭ 1,151 (+287.54%)
Mutual labels:  shopping-cart, cart
React With Redux Shop Ducks
shopping cart example with react and redux
Stars: ✭ 12 (-95.96%)
Mutual labels:  shopping-cart, cart
Online-Book-Store
An online Book Store createed with Python / Flask rest, MySql,Angular and Bootstrap
Stars: ✭ 76 (-74.41%)
Mutual labels:  shopping-cart, cart
Shoppingcart
REDAXO Warenkorb AddOn - Super flexibel, ohne Checkout
Stars: ✭ 28 (-90.57%)
Mutual labels:  shopping-cart, cart
Cezerin2
Cezerin2 is React and Node.js based eCommerce platform. React Shopping Cart. "All In One" App: Cezerin API + Cezerin Storefront + Cezerin Dashboard.
Stars: ✭ 144 (-51.52%)
Mutual labels:  shopping-cart, cart
Grandnode
Open source, headless, multi-tenant eCommerce platform built with .NET Core, MongoDB, AWS DocumentDB, Azure CosmosDB, Vue.js.
Stars: ✭ 1,768 (+495.29%)
Mutual labels:  shopping-cart, cart
Unchained
Headless & open-source e-commerce toolkit. The Unchained Engine is our core product and is written in Node.js ES6
Stars: ✭ 92 (-69.02%)
Mutual labels:  shopping-cart, cart
Arastta
Solid, Free, Open Source, Community Driven eCommerce
Stars: ✭ 251 (-15.49%)
Mutual labels:  shopping-cart, cart
cart
Shopping cart composer package
Stars: ✭ 109 (-63.3%)
Mutual labels:  shopping-cart, cart
Nopcommerce
The most popular open-source eCommerce shopping cart solution based on ASP.NET Core
Stars: ✭ 6,827 (+2198.65%)
Mutual labels:  shopping-cart, cart
Ecommwar
A leaderboard of the top open-source e-commerce platforms. Promoting the bests for building reliable stores.
Stars: ✭ 203 (-31.65%)
Mutual labels:  shopping-cart, cart
Sapper Ecommerce
Svelte ecommerce - Headless, Authentication, Cart & Checkout, TailwindCSS, Server Rendered, Proxy + API Integrated, Animations, Stores, Lazy Loading, Loading Indicators, Carousel, Instant Search, Faceted Filters, 1 command deploy to production, Open Source, MIT license. Join us as contributor ([email protected])
Stars: ✭ 289 (-2.69%)
Mutual labels:  shopping-cart, cart
Awesome Woocommerce
Plugins and code snippets to improve your WooCommerce store.
Stars: ✭ 279 (-6.06%)
Mutual labels:  shopping-cart, cart
awesome-ecommerce
Collect and develop Open Source or Free Projects for building ecommerce platform easy and fast and free
Stars: ✭ 39 (-86.87%)
Mutual labels:  shopping-cart, cart
Aimeos
Integrated online shop based on Laravel 8 and the Aimeos e-commerce framework
Stars: ✭ 2,354 (+692.59%)
Mutual labels:  shopping-cart, cart
Laravel Ecommerce Iyzico
Iyzico intigrated e-Commerce system that could be developed easily in simple level.
Stars: ✭ 81 (-72.73%)
Mutual labels:  shopping-cart, cart
Expresscart
A fully functioning Node.js shopping cart with Stripe, PayPal, Authorize.net, PayWay, Blockonomics, Adyen, Zip and Instore payments.
Stars: ✭ 2,069 (+596.63%)
Mutual labels:  shopping-cart, cart

react-use-cart

🛒 A lightweight shopping cart hook for React, Next.js, and Gatsby

Version Downloads/week License Forks on GitHub Forks on GitHub minified + gzip size Contributors

Why?

  • Bundle size
  • No dependencies
  • 💳 Not tied to any payment gateway, or checkout - create your own!
  • 🔥 Persistent carts with local storage, or your own adapter
  • ⭐️ Supports multiples carts per page
  • 🛒 Flexible cart item schema
  • 🥞 Works with Next, Gatsby, React
  • ♻️ Trigger your own side effects with cart handlers (on item add, update, remove)
  • 🛠 Built with TypeScript
  • Fully tested
  • 🌮 Used by Dines

Quick Start

Demo

import { CartProvider, useCart } from "react-use-cart";

function Page() {
  const { addItem } = useCart();

  const products = [
    {
      id: 1,
      name: "Malm",
      price: 9900,
      quantity: 1
    },
    {
      id: 2,
      name: "Nordli",
      price: 16500,
      quantity: 5
    },
    {
      id: 3,
      name: "Kullen",
      price: 4500,
      quantity: 1
    },
  ];

  return (
    <div>
      {products.map((p) => (
        <div key={p.id}>
          <button onClick={() => addItem(p)}>Add to cart</button>
        </div>
      ))}
    </div>
  );
}

function Cart() {
  const {
    isEmpty,
    totalUniqueItems,
    items,
    updateItemQuantity,
    removeItem,
  } = useCart();

  if (isEmpty) return <p>Your cart is empty</p>;

  return (
    <>
      <h1>Cart ({totalUniqueItems})</h1>

      <ul>
        {items.map((item) => (
          <li key={item.id}>
            {item.quantity} x {item.name} &mdash;
            <button
              onClick={() => updateItemQuantity(item.id, item.quantity - 1)}
            >
              -
            </button>
            <button
              onClick={() => updateItemQuantity(item.id, item.quantity + 1)}
            >
              +
            </button>
            <button onClick={() => removeItem(item.id)}>&times;</button>
          </li>
        ))}
      </ul>
    </>
  );
}

function App() {
  return (
    <CartProvider>
      <Page />
      <Cart />
    </CartProvider>
  );
}

Install

npm install react-use-cart # yarn add react-use-cart

CartProvider

You will need to wrap your application with the CartProvider component so that the useCart hook can access the cart state.

Carts are persisted across visits using localStorage, unless you specify your own storage adapter.

Usage

import React from "react";
import ReactDOM from "react-dom";
import { CartProvider } from "react-use-cart";

ReactDOM.render(
  <CartProvider>{/* render app/cart here */}</CartProvider>,
  document.getElementById("root")
);

Props

Prop Required Description
id No id for your cart to enable automatic cart retrieval via window.localStorage. If you pass a id then you can use multiple instances of CartProvider.
onSetItems No Triggered only when setItems invoked.
onItemAdd No Triggered on items added to your cart, unless the item already exists, then onItemUpdate will be invoked.
onItemUpdate No Triggered on items updated in your cart, unless you are setting the quantity to 0, then onItemRemove will be invoked.
onItemRemove No Triggered on items removed from your cart.
storage No Must return [getter, setter].
metadata No Custom global state on the cart. Stored inside of metadata.

useCart

The useCart hook exposes all the getter/setters for your cart state.

setItems(items)

The setItems method should be used to set all items in the cart. This will overwrite any existing cart items. A quantity default of 1 will be set for an item implicitly if no quantity is specified.

Args

  • items[] (Required): An array of cart item object. You must provide an id and price value for new items that you add to cart.

Usage

import { useCart } from "react-use-cart";

const { setItems } = useCart();

const products = [
  {
    id: "ckb64v21u000001ksgw2s42ku",
    name: "Fresh Foam 1080v9",
    brand: "New Balance",
    color: "Neon Emerald with Dark Neptune",
    size: "US 10",
    width: "B - Standard",
    sku: "W1080LN9",
    price: 15000,
  },
  {
    id: "cjld2cjxh0000qzrmn831i7rn",
    name: "Fresh Foam 1080v9",
    brand: "New Balance",
    color: "Neon Emerald with Dark Neptune",
    size: "US 9",
    width: "B - Standard",
    sku: "W1080LN9",
    price: 15000,
  },
];

setItems(products);

addItem(item, quantity)

The addItem method should be used to add items to the cart.

Args

  • item (Required): An object that represents your cart item. You must provide an id and price value for new items that you add to cart.
  • quantity (optional, default: 1): The amount of items you want to add.

Usage

import { useCart } from "react-use-cart";

const { addItem } = useCart();

const product = {
  id: "cjld2cjxh0000qzrmn831i7rn",
  name: "Fresh Foam 1080v9",
  brand: "New Balance",
  color: "Neon Emerald with Dark Neptune",
  size: "US 9",
  width: "B - Standard",
  sku: "W1080LN9",
  price: 15000,
};

addItem(product, 2);

updateItem(itemId, data)

The updateItem method should be used to update items in the cart.

Args

  • itemId (Required): The cart item id you want to update.
  • data (Required): The updated cart item object.

Usage

import { useCart } from "react-use-cart";

const { updateItem } = useCart();

updateItem("cjld2cjxh0000qzrmn831i7rn", {
  size: "UK 10",
});

updateItemQuantity(itemId, quantity)

The updateItemQuantity method should be used to update an items quantity value.

Args

  • itemId (Required): The cart item id you want to update.
  • quantity (Required): The updated cart item quantity.

Usage

import { useCart } from "react-use-cart";

const { updateItemQuantity } = useCart();

updateItemQuantity("cjld2cjxh0000qzrmn831i7rn", 1);

removeItem(itemId)

The removeItem method should be used to remove an item from the cart.

Args

  • itemId (Required): The cart item id you want to remove.

Usage

import { useCart } from "react-use-cart";

const { removeItem } = useCart();

removeItem("cjld2cjxh0000qzrmn831i7rn");

emptyCart()

The emptyCart() method should be used to remove all cart items, and resetting cart totals to the default 0 values.

Usage

import { useCart } from "react-use-cart";

const { emptyCart } = useCart();

emptyCart();

clearCartMetadata()

The clearCartMetadata() will reset the metadata to an empty object.

Usage

import { useCart } from "react-use-cart";

const { clearCartMetadata } = useCart();

clearCartMetadata();

setCartMetadata(object)

The setCartMetadata() will replace the metadata object on the cart. You must pass it an object.

Args

  • object: A object with key/value pairs. The key being a string.

Usage

import { useCart } from "react-use-cart";

const { setCartMetadata } = useCart();

setCartMetadata({ notes: "This is the only metadata" });

updateCartMetadata(object)

The updateCartMetadata() will update the metadata object on the cart. You must pass it an object. This will merge the passed object with the existing metadata.

Args

  • object: A object with key/value pairs. The key being a string.

Usage

import { useCart } from "react-use-cart";

const { updateCartMetadata } = useCart();

updateCartMetadata({ notes: "Leave in shed" });

items = []

This will return the current cart items in an array.

Usage

import { useCart } from "react-use-cart";

const { items } = useCart();

isEmpty = false

A quick and easy way to check if the cart is empty. Returned as a boolean.

Usage

import { useCart } from "react-use-cart";

const { isEmpty } = useCart();

getItem(itemId)

Get a specific cart item by id. Returns the item object.

Args

  • itemId (Required): The id of the item you're fetching.

Usage

import { useCart } from "react-use-cart";

const { getItem } = useCart();

const myItem = getItem("cjld2cjxh0000qzrmn831i7rn");

inCart(itemId)

Quickly check if an item is in the cart. Returned as a boolean.

Args

  • itemId (Required): The id of the item you're looking for.

Usage

import { useCart } from "react-use-cart";

const { inCart } = useCart();

inCart("cjld2cjxh0000qzrmn831i7rn") ? "In cart" : "Not in cart";

totalItems = 0

This returns the totaly quantity of items in the cart as an integer.

Usage

import { useCart } from "react-use-cart";

const { totalItems } = useCart();

totalUniqueItems = 0

This returns the total unique items in the cart as an integer.

Usage

import { useCart } from "react-use-cart";

const { totalUniqueItems } = useCart();

cartTotal = 0

This returns the total value of all items in the cart.

Usage

import { useCart } from "react-use-cart";

const { cartTotal } = useCart();

metadata = {}

This returns the metadata set with updateCartMetadata. This is useful for storing additional cart, or checkout values.

Usage

import { useCart } from "react-use-cart";

const { metadata } = useCart();

Contributors

Thanks goes to these wonderful people (emoji key):


Tobias Nielsen

💻

Craig Tweedy

💻

Jonathan Steele

💻

Scott Spence

💡

This project follows the all-contributors specification. Contributions of any kind welcome!

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].