mirror of
https://github.com/vercel/commerce.git
synced 2025-03-28 08:15:54 +00:00
* Minimal list/detail views working with Vendure * Implement useCart/useAddItem * Implement useUpdateItem & useRemoveItem * Implement useSearch * Add operations codegen, tidy up * Dummy checkout page * Implement auth/customer hooks * Use env var for Shop API url * Add some documentation * Improve error handling * Optimize preview image size * Fix accidental change * Update Vendure provider to latest changes * Vendure provider: split out gql operations, remove unused files * Update Vendure provider readme * Add local next.config to Vendure provider, update docs * Update to use demo server * Fix build errors * Use proxy for vendure api * Simplify instructions in Vendure readme * Refactor Vendure checkout api handler * Improve image quality
53 lines
1.5 KiB
TypeScript
53 lines
1.5 KiB
TypeScript
import { Cart, CartItemBody } from '@commerce/types'
|
|
import useAddItem, { UseAddItem } from '@commerce/cart/use-add-item'
|
|
import { CommerceError } from '@commerce/utils/errors'
|
|
import { MutationHook } from '@commerce/utils/types'
|
|
import { useCallback } from 'react'
|
|
import useCart from './use-cart'
|
|
import { AddItemToOrderMutation } from '../schema'
|
|
import { normalizeCart } from '../lib/normalize'
|
|
import { addItemToOrderMutation } from '../lib/mutations/add-item-to-order-mutation'
|
|
|
|
export default useAddItem as UseAddItem<typeof handler>
|
|
|
|
export const handler: MutationHook<Cart, {}, CartItemBody> = {
|
|
fetchOptions: {
|
|
query: addItemToOrderMutation,
|
|
},
|
|
async fetcher({ input, options, fetch }) {
|
|
if (
|
|
input.quantity &&
|
|
(!Number.isInteger(input.quantity) || input.quantity! < 1)
|
|
) {
|
|
throw new CommerceError({
|
|
message: 'The item quantity has to be a valid integer greater than 0',
|
|
})
|
|
}
|
|
|
|
const { addItemToOrder } = await fetch<AddItemToOrderMutation>({
|
|
...options,
|
|
variables: {
|
|
quantity: input.quantity || 1,
|
|
variantId: input.variantId,
|
|
},
|
|
})
|
|
|
|
if (addItemToOrder.__typename === 'Order') {
|
|
return normalizeCart(addItemToOrder)
|
|
}
|
|
throw new CommerceError(addItemToOrder)
|
|
},
|
|
useHook: ({ fetch }) => () => {
|
|
const { mutate } = useCart()
|
|
|
|
return useCallback(
|
|
async function addItem(input) {
|
|
const data = await fetch({ input })
|
|
await mutate(data, false)
|
|
return data
|
|
},
|
|
[fetch, mutate]
|
|
)
|
|
},
|
|
}
|