4
0
forked from crowetic/commerce

Added update item hook

This commit is contained in:
Luis Alvarez 2020-10-05 11:46:56 -05:00
parent 554d34b53b
commit 486c50a68b
2 changed files with 51 additions and 0 deletions

View File

@ -0,0 +1,40 @@
import type { Fetcher } from '@lib/commerce'
import { default as useCartUpdateItem } from '@lib/commerce/cart/use-update-item'
import type { Item } from '../api/cart'
import { Cart, useCart } from '.'
export type { Item }
export type UpdateItemInput = {
itemId: string
item: Item
}
function fetcher(fetch: Fetcher<Cart>, { itemId, item }: UpdateItemInput) {
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: '/api/bigcommerce/cart',
method: 'PUT',
body: { itemId, item },
})
}
export default function useUpdateItem() {
const { mutate } = useCart()
const fn = useCartUpdateItem<Cart, UpdateItemInput>(fetcher)
const updateItem: typeof fn = async (input) => {
const data = await fn(input)
mutate(data)
return data
}
return updateItem
}

View File

@ -0,0 +1,11 @@
import { Fetcher, useCommerce } from '..'
export default function useUpdateItem<T, Input>(
fetcher: (fetch: Fetcher<T>, input: Input) => T | Promise<T>
) {
const { fetcher: fetch } = useCommerce()
return async function updateItem(input: Input) {
return fetcher(fetch, input)
}
}