4
0
forked from crowetic/commerce
Files
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-price.tsx
commerce
colors.ts
logger.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
commerce/lib/bigcommerce/cart/use-add-item.tsx
Luis Alvarez 8e42fdd25d Minor change
2020-10-10 10:06:28 -05:00

56 lines
1.3 KiB
TypeScript

import { useCallback } from 'react'
import { HookFetcher } from '@lib/commerce/utils/types'
import useCartAddItem from '@lib/commerce/cart/use-add-item'
import type { ItemBody, AddItemBody } from '../api/cart'
import useCart, { Cart } from './use-cart'
const defaultOpts = {
url: '/api/bigcommerce/cart',
method: 'POST',
}
export type AddItemInput = ItemBody
export const fetcher: HookFetcher<Cart, AddItemBody> = (
options,
{ item },
fetch
) => {
if (
item.quantity &&
(!Number.isInteger(item.quantity) || item.quantity! < 1)
) {
throw new Error(
'The item quantity has to be a valid integer greater than 0'
)
}
return fetch({
url: options?.url ?? defaultOpts.url,
method: options?.method ?? defaultOpts.method,
body: { item },
})
}
export function extendHook(customFetcher: typeof fetcher) {
const useAddItem = () => {
const { mutate } = useCart()
const fn = useCartAddItem<Cart, AddItemBody>(defaultOpts, customFetcher)
return useCallback(
async function addItem(input: AddItemInput) {
const data = await fn({ item: input })
await mutate(data, false)
return data
},
[fn, mutate]
)
}
useAddItem.extend = extendHook
return useAddItem
}
export default extendHook(fetcher)