mirror of
https://github.com/vercel/commerce.git
synced 2025-08-13 04:11:23 +00:00
.vscode
assets
components
config
framework
bigcommerce
commerce
saleor
shopify
swell
vendure
api
auth
cart
index.ts
use-add-item.tsx
use-cart.tsx
use-remove-item.tsx
use-update-item.tsx
customer
product
types
utils
wishlist
.env.template
README.md
codegen.json
commerce.config.json
fetcher.ts
index.tsx
next.config.js
provider.ts
schema.d.ts
schema.graphql
lib
pages
public
.editorconfig
.env.template
.gitignore
.prettierignore
.prettierrc
README.md
codegen.bigcommerce.json
codegen.json
commerce.config.json
global.d.ts
license.md
next-env.d.ts
next.config.js
package.json
postcss.config.js
tailwind.config.js
tsconfig.json
yarn.lock
53 lines
1.5 KiB
TypeScript
53 lines
1.5 KiB
TypeScript
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 '../utils/normalize'
|
|
import { addItemToOrderMutation } from '../utils/mutations/add-item-to-order-mutation'
|
|
import { AddItemHook } from '../types/cart'
|
|
|
|
export default useAddItem as UseAddItem<typeof handler>
|
|
|
|
export const handler: MutationHook<AddItemHook> = {
|
|
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]
|
|
)
|
|
},
|
|
}
|