forked from crowetic/commerce
Added update item hook
This commit is contained in:
parent
554d34b53b
commit
486c50a68b
40
lib/bigcommerce/cart/use-update-item.tsx
Normal file
40
lib/bigcommerce/cart/use-update-item.tsx
Normal 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
|
||||
}
|
11
lib/commerce/cart/use-update-item.tsx
Normal file
11
lib/commerce/cart/use-update-item.tsx
Normal 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)
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user