4
0
forked from crowetic/commerce

Added useCustomer hook

This commit is contained in:
Luis Alvarez 2020-10-21 10:23:05 -05:00
parent 2aae613f1b
commit d98897a7e3
4 changed files with 72 additions and 6 deletions

View File

@ -14,12 +14,7 @@ export const fetcher: HookFetcher<Cart | null, CartInput> = (
{ cartId },
fetch
) => {
return cartId
? fetch({
url: options?.url,
query: options?.query,
})
: null
return cartId ? fetch({ ...options }) : null
}
export function extendHook(

View File

@ -0,0 +1,40 @@
import { ConfigInterface } from 'swr'
import { HookFetcher } from '@lib/commerce/utils/types'
import useCommerceCustomer, { CustomerInput } from '@lib/commerce/use-customer'
import type { Customer, CustomerData } from './api/customers'
const defaultOpts = {
url: '/api/bigcommerce/customer',
}
export type { Customer }
export const fetcher: HookFetcher<CustomerData | null, CustomerInput> = (
options,
{ cartId },
fetch
) => {
return cartId ? fetch({ ...options }) : null
}
export function extendHook(
customFetcher: typeof fetcher,
swrOptions?: ConfigInterface
) {
const useCustomer = () => {
const cart = useCommerceCustomer<CustomerData | null>(
defaultOpts,
[],
customFetcher,
{ revalidateOnFocus: false, ...swrOptions }
)
return cart
}
useCustomer.extend = extendHook
return useCustomer
}
export default extendHook(fetcher)

View File

@ -0,0 +1,30 @@
import { responseInterface, ConfigInterface } from 'swr'
import Cookies from 'js-cookie'
import type { HookInput, HookFetcher, HookFetcherOptions } from './utils/types'
import useData from './utils/use-data'
import { useCommerce } from '.'
export type CustomerResponse<T> = responseInterface<T, Error>
export type CustomerInput = {
cartId: string | undefined
}
export default function useCustomer<T>(
options: HookFetcherOptions,
input: HookInput,
fetcherFn: HookFetcher<T | null, CustomerInput>,
swrOptions?: ConfigInterface<T | null>
) {
// TODO: Replace this with the login cookie
const { cartCookie } = useCommerce()
const fetcher: typeof fetcherFn = (options, input, fetch) => {
input.cartId = Cookies.get(cartCookie)
return fetcherFn(options, input, fetch)
}
const response = useData(options, input, fetcher, swrOptions)
return response as CustomerResponse<T>
}

View File

@ -12,6 +12,7 @@ export default function useData<T, Input = any>(
const fetcher = (url?: string, query?: string, ...args: any[]) => {
return fetcherFn(
{ url, query },
// Transform the input array into an object
args.reduce((obj, val, i) => {
obj[input[i][0]!] = val
return obj