mirror of
https://github.com/vercel/commerce.git
synced 2025-06-18 21:21:21 +00:00
Checkpoint
This commit is contained in:
parent
465a18b628
commit
f3751cd389
68
framework/csv/api/cart.ts
Normal file
68
framework/csv/api/cart.ts
Normal file
@ -0,0 +1,68 @@
|
||||
import { LineItem } from '../types'
|
||||
|
||||
const api = {
|
||||
get: (): LineItem[] => {
|
||||
if (!process.browser) {
|
||||
return []
|
||||
}
|
||||
|
||||
const raw = localStorage.getItem('cart')
|
||||
|
||||
if (!raw) {
|
||||
return []
|
||||
}
|
||||
|
||||
return JSON.parse(raw) as LineItem[]
|
||||
},
|
||||
set: (items: LineItem[]) => {
|
||||
localStorage.setItem('cart', JSON.stringify(items))
|
||||
},
|
||||
add: (item: LineItem) => {
|
||||
const items = api.get()
|
||||
const itemIndex = items.findIndex(
|
||||
(_item) => _item.productId === item.productId
|
||||
)
|
||||
|
||||
if (itemIndex >= 0) {
|
||||
items[itemIndex].quantity = (items[itemIndex].quantity || 0) + 1
|
||||
} else {
|
||||
items.push(item)
|
||||
}
|
||||
|
||||
api.set(items)
|
||||
|
||||
return items
|
||||
},
|
||||
remove: (item: LineItem) => {
|
||||
const items = api.get()
|
||||
const itemIndex = items.findIndex(
|
||||
(_item) => _item.productId === item.productId
|
||||
)
|
||||
|
||||
if (itemIndex >= 0) {
|
||||
items.splice(itemIndex, 1)
|
||||
}
|
||||
|
||||
api.set(items)
|
||||
|
||||
return items
|
||||
},
|
||||
update: (item: LineItem) => {
|
||||
const items = api.get()
|
||||
const itemIndex = items.findIndex(
|
||||
(_item) => _item.productId === item.productId
|
||||
)
|
||||
|
||||
if (itemIndex >= 0) {
|
||||
items[itemIndex] = item
|
||||
} else {
|
||||
items.push(item)
|
||||
}
|
||||
|
||||
api.set(items)
|
||||
|
||||
return items
|
||||
},
|
||||
}
|
||||
|
||||
export default api
|
@ -1,7 +1,11 @@
|
||||
import { Cart, CartItemBody } from '../types'
|
||||
import { Cart, CartItemBody, LineItem } from '../types'
|
||||
|
||||
import api from '../api/cart'
|
||||
|
||||
export default function useAddItem() {
|
||||
return (_item: CartItemBody): Cart => {
|
||||
return (item: CartItemBody): Cart => {
|
||||
api.add(item as LineItem)
|
||||
|
||||
return (null as unknown) as Cart
|
||||
}
|
||||
}
|
||||
|
@ -1,4 +1,6 @@
|
||||
import { Cart } from '@framework/types'
|
||||
import { Cart } from '../types'
|
||||
|
||||
import api from '../api/cart'
|
||||
|
||||
export interface CartResponse {
|
||||
data: Cart | null
|
||||
@ -7,6 +9,10 @@ export interface CartResponse {
|
||||
}
|
||||
|
||||
export default function useCart(): CartResponse {
|
||||
const cart = api.get()
|
||||
|
||||
console.log({ cart })
|
||||
|
||||
return {
|
||||
data: null,
|
||||
isLoading: false,
|
||||
|
Loading…
x
Reference in New Issue
Block a user