summaryrefslogtreecommitdiff
path: root/examples/with-nanostores/src/cartStore.ts
blob: f490a2447f04b7c8cf09f91f578f91640fdc4a74 (plain) (blame)
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
import { atom, map } from 'nanostores';

export const isCartOpen = atom(false);

export type CartItem = {
	id: string;
	name: string;
	imageSrc: string;
	quantity: number;
};

export type CartItemDisplayInfo = Pick<CartItem, 'id' | 'name' | 'imageSrc'>;

export const cartItems = map<Record<string, CartItem>>({});

export function addCartItem({ id, name, imageSrc }) {
	const existingEntry = cartItems.get()[id];
	if (existingEntry) {
		cartItems.setKey(id, {
			...existingEntry,
			quantity: existingEntry.quantity + 1,
		});
	} else {
		cartItems.setKey(id, {
			id,
			name,
			imageSrc,
			quantity: 1,
		});
	}
}