-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathuseShoppingCart.ts
More file actions
34 lines (22 loc) · 794 Bytes
/
useShoppingCart.ts
File metadata and controls
34 lines (22 loc) · 794 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { useState } from 'react';
import { Product, ProductInCart } from '../interfaces/interfaces';
export const useShoppingCart = () => {
const [ shoppingCart, setShoppingCart ] = useState<{ [key:string]: ProductInCart }>({});
const onProductCountChange = ({ count, product }: { count:number, product: Product }) => {
console.log({ count })
setShoppingCart( oldShoppingCart => {
if( count === 0 ) {
const { [product.id]: toDelete, ...rest } = oldShoppingCart;
return rest;
}
return {
...oldShoppingCart,
[ product.id ]: { ...product, count }
}
})
}
return {
shoppingCart,
onProductCountChange,
}
}