4
0
forked from crowetic/commerce

Updated the useRemoveItem hook

This commit is contained in:
Luis Alvarez
2020-10-09 10:44:54 -05:00
parent c2096a8ab4
commit cc0e62cd7e
3 changed files with 42 additions and 23 deletions

View File

@@ -1,34 +1,51 @@
import { useCallback } from 'react'
import type { Fetcher } from '@lib/commerce'
import { HookFetcher } from '@lib/commerce/utils/types'
import { default as useCartRemoveItem } from '@lib/commerce/cart/use-remove-item'
import type { RemoveItemBody } from '../api/cart'
import { Cart, useCart } from '.'
const defaultOpts = {
url: '/api/bigcommerce/cart',
method: 'DELETE',
}
export type RemoveItemInput = {
id: string
}
export function fetcher(
fetch: Fetcher<Cart | null>,
{ itemId }: RemoveItemBody
) {
export const fetcher: HookFetcher<Cart | null, RemoveItemBody> = (
options,
{ itemId },
fetch
) => {
return fetch({
url: '/api/bigcommerce/cart',
method: 'DELETE',
url: options.url!,
method: options.method!,
body: { itemId },
})
}
export default function useRemoveItem(item?: any) {
const { mutate } = useCart()
const fn = useCartRemoveItem<Cart | null, RemoveItemBody>(fetcher)
function extend(customFetcher: typeof fetcher) {
const useRemoveItem = (item?: any) => {
const { mutate } = useCart()
const fn = useCartRemoveItem<Cart | null, RemoveItemBody>(
defaultOpts,
customFetcher
)
return useCallback(
async function removeItem(input: RemoveItemInput) {
const data = await fn({ itemId: input.id ?? item?.id })
await mutate(data, false)
return data
},
[fn, mutate]
)
return useCallback(
async function removeItem(input: RemoveItemInput) {
const data = await fn({ itemId: input.id ?? item?.id })
await mutate(data, false)
return data
},
[fn, mutate]
)
}
useRemoveItem.extend = extend
return useRemoveItem
}
export default extend(fetcher)