All files / composables useShopCart.ts

100% Statements 25/25
100% Branches 14/14
100% Functions 4/4
100% Lines 25/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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    1x 3x 3x 3x 3x 3x 3x 1x 3x 3x 4x 4x 3x 2x 2x 2x 2x 3x 1x 1x 1x 3x 3x 3x 3x  
import type {CartLine, Product} from '~/types/shop'
 
export function useShopCart() {
    const cart = useState<CartLine[]>('cart', () => [])
    const client = typeof window !== 'undefined'
    if (client && !cart.value.length) {
        try {
            cart.value = JSON.parse(localStorage.getItem('angel-cart') || '[]')
        } catch {
        }
    }
    const save = () => {
        if (client) localStorage.setItem('angel-cart', JSON.stringify(cart.value))
    }
    const add = (product: Product) => {
        const line = cart.value.find(l => l.product.id === product.id);
        if (line) line.quantity++; else cart.value.push({product, quantity: 1});
        save()
    }
    const remove = (id: number) => {
        cart.value = cart.value.filter(l => l.product.id !== id);
        save()
    }
    const count = computed(() => cart.value.reduce((s, l) => s + l.quantity, 0));
    const total = computed(() => cart.value.reduce((s, l) => s + l.product.priceCents * l.quantity, 0))
    return {cart, add, remove, count, total, save}
}