import { useSelector } from 'react-redux' ; import { useRouter } from 'next/router' ; import { checkoutPage , CartProduct } from '@core' ; import { useAppDispatch } from '@hooks' ; import { addToCartAction , removeFromCartAction , increaseCartInventoryAction , emptyCartAction , decreaseCartInventoryAction , } from './store/actions' ; import { cartProductsSelector , cartProductsTotalCostSelector , } from './store/selectors' ; import { AddToCartActionPayload , IncreaseCartInventoryActionPayload , DecreaseCartInventoryActionPayload , RemoveFromCartActionPayload , } from './store/types' ; export interface UseCart { totalPrice : number ; products : CartProduct [ ] ; totalQuantity : number ; actions : { addToCart : ( payload : AddToCartActionPayload ) => void ; buyNow : ( payload : AddToCartActionPayload ) => void ; removeFromCart : ( payload : RemoveFromCartActionPayload ) => void ; increaseCartInventory : ( paylaod : IncreaseCartInventoryActionPayload ) => void ; decreaseCartInventory : ( paylaod : DecreaseCartInventoryActionPayload ) => void ; emptyCart : ( ) => void ; } ; } const useCart = ( ) => { const dispatch = useAppDispatch ( ) ; const totalPrice = useSelector ( cartProductsTotalCostSelector ) ; const products = useSelector ( cartProductsSelector ) ; const totalQuantity = products . reduce ( ( acc , curr ) => acc + curr . quantity , 0 ) ; const router = useRouter ( ) ; const addToCart = ( { product , } ) => dispatch ( addToCartAction ( { product } ) ) ; const buyNow = ( { product , } ) => { dispatch ( addToCartAction ( { product } ) ) ; router . push ( checkoutPage ( ) ) ; } ; const removeFromCart = ( { productId } ) => dispatch ( removeFromCartAction ( { productId } ) ) ; const increaseCartInventory = ( { productId } ) => dispatch ( increaseCartInventoryAction ( { productId } ) ) ; const decreaseCartInventory = ( { productId } ) => dispatch ( decreaseCartInventoryAction ( { productId } ) ) ; const emptyCart = ( ) => dispatch ( emptyCartAction ( ) ) ; return { totalPrice , products , totalQuantity , actions : { addToCart , buyNow , removeFromCart , increaseCartInventory , decreaseCartInventory , emptyCart , } , } ; } ; export default useCart ;