forked from crowetic/commerce
assets
components
config
lib
bigcommerce
api
cart
use-add-item.tsx
use-cart-actions.tsx
use-cart.tsx
use-remove-item.tsx
use-update-item.tsx
products
scripts
wishlist
index.tsx
schema.d.ts
schema.graphql
use-customer.tsx
use-login.tsx
use-logout.tsx
use-price.tsx
use-signup.tsx
commerce
browser.ts
colors.ts
logger.ts
range-map.ts
to-pixels.ts
pages
public
utils
.gitignore
.prettierignore
README.md
codegen.json
global.d.ts
next-env.d.ts
next.config.js
package.json
postcss.config.js
tailwind.config.js
tsconfig.json
yarn.lock
51 lines
1.2 KiB
TypeScript
51 lines
1.2 KiB
TypeScript
import type { HookFetcher } from '@lib/commerce/utils/types'
|
|
import type { SwrOptions } from '@lib/commerce/utils/use-data'
|
|
import useCommerceCart, { CartInput } from '@lib/commerce/cart/use-cart'
|
|
import type { Cart } from '../api/cart'
|
|
|
|
const defaultOpts = {
|
|
url: '/api/bigcommerce/cart',
|
|
method: 'GET',
|
|
}
|
|
|
|
export type { Cart }
|
|
|
|
export const fetcher: HookFetcher<Cart | null, CartInput> = (
|
|
options,
|
|
{ cartId },
|
|
fetch
|
|
) => {
|
|
return cartId ? fetch({ ...defaultOpts, ...options }) : null
|
|
}
|
|
|
|
export function extendHook(
|
|
customFetcher: typeof fetcher,
|
|
swrOptions?: SwrOptions<Cart | null, CartInput>
|
|
) {
|
|
const useCart = () => {
|
|
const response = useCommerceCart(defaultOpts, [], customFetcher, {
|
|
revalidateOnFocus: false,
|
|
...swrOptions,
|
|
})
|
|
|
|
// Uses a getter to only calculate the prop when required
|
|
// response.data is also a getter and it's better to not trigger it early
|
|
Object.defineProperty(response, 'isEmpty', {
|
|
get() {
|
|
return Object.values(response.data?.line_items ?? {}).every(
|
|
(items) => !items.length
|
|
)
|
|
},
|
|
set: (x) => x,
|
|
})
|
|
|
|
return response
|
|
}
|
|
|
|
useCart.extend = extendHook
|
|
|
|
return useCart
|
|
}
|
|
|
|
export default extendHook(fetcher)
|