4
0
forked from crowetic/commerce
commerce/packages/commercejs/src/cart/use-add-item.tsx
Catalin Pinte 6c2610584d
Update types (#831)
* Update product types

* Cart types progress, add zod & initial schema validator

* Update normalize.ts

* Update with-schema-parser.ts

* Updated types, schemas & providers

* Fix providers after schema parse errors

* Fix paths

* More provider fixes

* Fix kibocommerce & commercejs

* Add customer updated types & fixes

* Add checkout & customer types

* Import core types only from commerce

* Update tsconfig.json

* Convert hooks interfaces to types

* Requested changes

* Change to relative paths

* Move Zod dependency
2022-10-05 09:02:29 +03:00

46 lines
1.3 KiB
TypeScript

import type { AddItemHook } from '@vercel/commerce/types/cart'
import type { MutationHook } from '@vercel/commerce/utils/types'
import { useCallback } from 'react'
import useAddItem, { UseAddItem } from '@vercel/commerce/cart/use-add-item'
import type { CommercejsCart } from '../types'
import { normalizeCart } from '../utils/normalize-cart'
import useCart from './use-cart'
export default useAddItem as UseAddItem<typeof handler>
export const handler: MutationHook<AddItemHook> = {
fetchOptions: {
query: 'cart',
method: 'add',
},
async fetcher({ input: item, options, fetch }) {
// Frontend stringifies variantId even if undefined.
const hasVariant = !item.variantId || item.variantId !== 'undefined'
const variables = [item.productId, item?.quantity || 1]
if (hasVariant) {
variables.push(item.variantId)
}
const { cart } = await fetch<{ cart: CommercejsCart }>({
query: options.query,
method: options.method,
variables,
})
return normalizeCart(cart)
},
useHook: ({ fetch }) =>
function useHook() {
const { mutate } = useCart()
return useCallback(
async function addItem(input) {
const cart = await fetch({ input })
await mutate(cart, false)
return cart
},
[mutate]
)
},
}