import Cookies from 'js-cookie' import type { Cart } from '../types' import type { Prop, HookFetcherFn, UseHookInput, UseHookResponse, } from '../utils/types' import useData from '../utils/use-data' import { Provider, useCommerce } from '..' export type FetchCartInput = { cartId?: Cart['id'] } export type UseCartHandler
= Prop< Prop
, 'useCart' > export type UseCartInput
= UseHookInput = UseHookResponse<
UseCartHandler
>
export type UseCart = Partial<
UseCartInput
> extends UseCartInput
? (input?: UseCartInput ) => CartResponse
: (input: UseCartInput ) => CartResponse
export const fetcher: HookFetcherFn (
input: UseCartInput = {}
) {
const { providerRef, fetcherRef, cartCookie } = useCommerce ()
const provider = providerRef.current
const opts = provider.cart?.useCart
const fetcherFn = opts?.fetcher ?? fetcher
const useHook = opts?.useHook ?? ((ctx) => ctx.useData())
const wrapper: typeof fetcher = (context) => {
context.input.cartId = Cookies.get(cartCookie)
return fetcherFn(context)
}
return useHook({
input,
useData(ctx) {
const response = useData(
{ ...opts!, fetcher: wrapper },
ctx?.input ?? [],
provider.fetcher ?? fetcherRef.current,
ctx?.swrOptions ?? input.swrOptions
)
return response
},
})
}