4
0
forked from crowetic/commerce
commerce/framework/swell/cart/use-cart.tsx
ghoskin 4d85b43a30
Update Swell Provider (#359)
* fix update cart item

* update types

* update checkout

* update get-page, cleanup types

* revert change to incorrect file

* cleanup

Co-authored-by: Greg Hoskin <greghoskin@Gregs-MacBook-Pro.local>
2021-06-14 17:37:18 -03:00

38 lines
1009 B
TypeScript

import useCart, { UseCart } from '@commerce/cart/use-cart'
import { SWRHook } from '@commerce/utils/types'
import { useMemo } from 'react'
import { normalizeCart } from '../utils/normalize'
import { checkoutCreate, checkoutToCart } from './utils'
import type { GetCartHook } from '@commerce/types/cart'
export default useCart as UseCart<typeof handler>
export const handler: SWRHook<GetCartHook> = {
fetchOptions: {
query: 'cart',
method: 'get',
},
async fetcher({ fetch }) {
const cart = await checkoutCreate(fetch)
return cart ? normalizeCart(cart) : null
},
useHook: ({ useData }) => (input) => {
const response = useData({
swrOptions: { revalidateOnFocus: false, ...input?.swrOptions },
})
return useMemo(
() =>
Object.create(response, {
isEmpty: {
get() {
return (response.data?.lineItems.length ?? 0) <= 0
},
enumerable: true,
},
}),
[response]
)
},
}