From 486c50a68b2f8c8f4273db49c5b3dbd5bf00b6f1 Mon Sep 17 00:00:00 2001 From: Luis Alvarez Date: Mon, 5 Oct 2020 11:46:56 -0500 Subject: [PATCH] Added update item hook --- lib/bigcommerce/cart/use-update-item.tsx | 40 ++++++++++++++++++++++++ lib/commerce/cart/use-update-item.tsx | 11 +++++++ 2 files changed, 51 insertions(+) create mode 100644 lib/bigcommerce/cart/use-update-item.tsx create mode 100644 lib/commerce/cart/use-update-item.tsx diff --git a/lib/bigcommerce/cart/use-update-item.tsx b/lib/bigcommerce/cart/use-update-item.tsx new file mode 100644 index 000000000..f82bca5a3 --- /dev/null +++ b/lib/bigcommerce/cart/use-update-item.tsx @@ -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, { 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(fetcher) + const updateItem: typeof fn = async (input) => { + const data = await fn(input) + mutate(data) + return data + } + + return updateItem +} diff --git a/lib/commerce/cart/use-update-item.tsx b/lib/commerce/cart/use-update-item.tsx new file mode 100644 index 000000000..2d076129a --- /dev/null +++ b/lib/commerce/cart/use-update-item.tsx @@ -0,0 +1,11 @@ +import { Fetcher, useCommerce } from '..' + +export default function useUpdateItem( + fetcher: (fetch: Fetcher, input: Input) => T | Promise +) { + const { fetcher: fetch } = useCommerce() + + return async function updateItem(input: Input) { + return fetcher(fetch, input) + } +}