Skip to content

Commit

Permalink
feat: create trigger onEmptyCart (#129)
Browse files Browse the repository at this point in the history
* feat: add prop onEmptyCart

* feat(readme): add prop onEmptyCart

* feat(tests): add test to prop onEmptyCart
  • Loading branch information
mariosantosdev authored Jun 16, 2023
1 parent 53c19fd commit 492e979
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 4 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ ReactDOM.render(
| `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. |
| `onEmptyCart` | _No_ | Triggered on empty cart. |
| `storage` | _No_ | Must return `[getter, setter]`. |
| `metadata` | _No_ | Custom global state on the cart. Stored inside of `metadata`. |
## `useCart`
Expand Down
11 changes: 7 additions & 4 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ export const CartProvider: React.FC<{
onItemAdd?: (payload: Item) => void;
onItemUpdate?: (payload: object) => void;
onItemRemove?: (id: Item["id"]) => void;
onEmptyCart?: () => void;
storage?: (
key: string,
initialValue: string
Expand All @@ -187,6 +188,7 @@ export const CartProvider: React.FC<{
onItemAdd,
onItemUpdate,
onItemRemove,
onEmptyCart,
storage = useLocalStorage,
metadata,
}) => {
Expand Down Expand Up @@ -291,10 +293,11 @@ export const CartProvider: React.FC<{
onItemRemove && onItemRemove(id);
};

const emptyCart = () =>
dispatch({
type: "EMPTY_CART",
});
const emptyCart = () => {
dispatch({ type: "EMPTY_CART" });

onEmptyCart && onEmptyCart();
}

const getItem = (id: Item["id"]) =>
state.items.find((i: Item) => i.id === id);
Expand Down
15 changes: 15 additions & 0 deletions test/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,21 @@ describe("emptyCart", () => {
expect(result.current.totalUniqueItems).toBe(0);
expect(result.current.isEmpty).toBe(true);
});

test("triggers onEmptyCart when empty cart", () => {
let called = false;

const wrapper: FC<Props> = ({ children }) => (
<CartProvider onEmptyCart={() => (called = true)}>
{children}
</CartProvider>
);

const { result } = renderHook(() => useCart(), { wrapper });

act(() => result.current.emptyCart());
expect(called).toBe(true);
});
});

describe("updateCartMetadata", () => {
Expand Down

0 comments on commit 492e979

Please sign in to comment.