Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions packages/plugin-ecommerce/src/react/provider/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ const defaultContext: EcommerceContextType = {
incrementItem: async () => {},
initiatePayment: async () => {},
paymentMethods: [],
refreshCart: async () => {},
removeItem: async () => {},
setCurrency: () => {},
updateAddress: async () => {},
Expand Down Expand Up @@ -212,6 +213,12 @@ export const EcommerceProvider: React.FC<ContextProps> = ({
[baseAPIURL, cartQuery, cartsSlug],
)

const refreshCart = useCallback<EcommerceContextType['refreshCart']>(async () => {
if (!cartID) {return}
const updatedCart = await getCart(cartID)
setCart(updatedCart)
}, [cartID, getCart])

const deleteCart = useCallback(
async (cartID: DefaultDocumentIDType) => {
const response = await fetch(`${baseAPIURL}/${cartsSlug}/${cartID}`, {
Expand Down Expand Up @@ -802,6 +809,7 @@ export const EcommerceProvider: React.FC<ContextProps> = ({
incrementItem,
initiatePayment,
paymentMethods,
refreshCart,
removeItem,
selectedPaymentMethod,
setCurrency,
Expand Down Expand Up @@ -864,13 +872,22 @@ export const useCurrency = () => {
}

export function useCart<T extends CartsCollection>() {
const { addItem, cart, clearCart, decrementItem, incrementItem, removeItem } = useEcommerce()
const { addItem, cart, clearCart, decrementItem, incrementItem, refreshCart, removeItem } =
useEcommerce()

if (!addItem) {
throw new Error('useCart must be used within an EcommerceProvider')
}

return { addItem, cart: cart as T, clearCart, decrementItem, incrementItem, removeItem }
return {
addItem,
cart: cart as T,
clearCart,
decrementItem,
incrementItem,
refreshCart,
removeItem,
}
}

export const usePayments = () => {
Expand Down
4 changes: 4 additions & 0 deletions packages/plugin-ecommerce/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -864,6 +864,10 @@ export type EcommerceContextType<T extends EcommerceCollections = EcommerceColle
options?: { additionalData: Record<string, unknown> },
) => Promise<unknown>
paymentMethods: PaymentAdapterClient[]
/**
* Refresh the cart.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A little light on detail for what I would want to see from this jsdoc

*/
refreshCart: () => Promise<void>
/**
* Remove an item from the cart by its index ID.
*/
Expand Down
Loading