CartProvider
CartProvider
is a React component that wraps an entire app, providing it with the necessary context to manage shopping cart operations. The component handles actions in the cart such as adding, removing, and updating items, and ensures the cart state is consistent across the application. For more details on these actions, see useCart
.Import
_10import { CartProvider } from '@faststore/sdk'
Usage
The following example shows how to wrap your application with
CartProvider
to manage shopping cart operations:
_10import { CartProvider } from '@faststore/sdk'_10_10function App () {_10 return (_10 <CartProvider mode="pure">_10 {children}_10 </CartProvider>_10 )_10}
The
mode
property is required and determines how cart operations are handled. It can be set to either optimistic
or pure
:optimistic
: Updates the cart optimistically, assuming the operation will succeed.
pure
: Waits for the operation to complete before updating the cart.Props
The
CartProvider
component accepts the following properties and functions:Variable name | Type | Description |
---|---|---|
mode (required) | optimistic or pure | Defines how cart operations are processed. |
initialCart | Cart | Initial cart state used before hydrating it from IndexedDB. If not provided, the cart will start empty. |
namespace | string | A unique identifier for the cart. This is used to avoid collisions in IndexedDB when multiple carts are used in the same application. |
onItemAdd | (newItem: Item, oldItem?: Item) => void | Callback function called when an item is added to the cart. |
onItemRemove | (item?: Item) => void | Callback function called when an item is removed from the cart. |
onItemUpdate | (newItem: Item, oldItem?: Item) => void` | Callback function called when an item is updated. |
onValidateCart | (cart: Cart) => Promise<Cart /> null> | Callback function called whenever the cart changes. This is only available in optimistic mode and can be used to validate or modify the cart before changes are applied. |