Added initial version of useAddItem

This commit is contained in:
Luis Alvarez
2021-02-16 21:14:11 -05:00
parent 75d485d35a
commit c02d7fec62
7 changed files with 145 additions and 96 deletions

View File

@@ -1,9 +1,6 @@
import { useCallback } from 'react'
import type { HookFetcher } from '@commerce/utils/types'
import type { MutationHandler } from '@commerce/utils/types'
import { CommerceError } from '@commerce/utils/errors'
import useCartAddItem, {
AddItemInput as UseAddItemInput,
} from '@commerce/cart/use-add-item'
import useAddItem, { UseAddItem } from '@commerce/cart/use-add-item'
import { normalizeCart } from '../lib/normalize'
import type {
AddCartItemBody,
@@ -12,55 +9,45 @@ import type {
CartItemBody,
} from '../types'
import useCart from './use-cart'
import { BigcommerceProvider } from '..'
const defaultOpts = {
url: '/api/bigcommerce/cart',
method: 'POST',
}
export type AddItemInput = UseAddItemInput<CartItemBody>
export default useAddItem as UseAddItem<BigcommerceProvider, CartItemBody>
export const fetcher: HookFetcher<Cart, AddCartItemBody> = async (
options,
{ item },
fetch
) => {
if (
item.quantity &&
(!Number.isInteger(item.quantity) || item.quantity! < 1)
) {
throw new CommerceError({
message: 'The item quantity has to be a valid integer greater than 0',
export const handler: MutationHandler<Cart, {}, AddCartItemBody> = {
fetchOptions: {
url: '/api/bigcommerce/cart',
method: 'GET',
},
async fetcher({ input: { item }, options, fetch }) {
if (
item.quantity &&
(!Number.isInteger(item.quantity) || item.quantity! < 1)
) {
throw new CommerceError({
message: 'The item quantity has to be a valid integer greater than 0',
})
}
const data = await fetch<BigcommerceCart, AddCartItemBody>({
...defaultOpts,
...options,
body: { item },
})
}
const data = await fetch<BigcommerceCart, AddCartItemBody>({
...defaultOpts,
...options,
body: { item },
})
return normalizeCart(data)
}
export function extendHook(customFetcher: typeof fetcher) {
const useAddItem = () => {
return normalizeCart(data)
},
useHook() {
const { mutate } = useCart()
const fn = useCartAddItem(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
return async function addItem({ input, fetch }) {
const data = await fetch({ input })
await mutate(data, false)
return data
}
},
}
export default extendHook(fetcher)