4
0
forked from crowetic/commerce

Hook changes

This commit is contained in:
Luis Alvarez 2020-10-04 13:12:41 -05:00
parent b8d50ea528
commit 0ad9ac0d5d
6 changed files with 61 additions and 15 deletions

View File

@ -0,0 +1,19 @@
import { Fetcher } from '@lib/commerce'
import { default as useCartAddItem } from '@lib/commerce/cart/use-add-item'
import { Cart } from '.'
async function fetcher(fetch: Fetcher<Cart>, { item }: { item: any }) {
const res = await fetch({ url: '/api/cart' })
// {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json',
// },
// body: JSON.stringify({ product }),
// }
}
export default function useAddItem() {
return useCartAddItem<Cart, { item: any }>(fetcher)
}

View File

@ -21,19 +21,17 @@ async function getError(res: Response) {
return { message: await getText(res) }
}
async function fetcher(url: string, query: string) {
const res = await fetch(url)
if (res.ok) {
return res.json()
}
throw await getError(res)
}
export const bigcommerceConfig: CommerceConfig = {
locale: 'en-us',
fetcher,
async fetcher({ url, query }) {
const res = await fetch(url!)
if (res.ok) {
return res.json()
}
throw await getError(res)
},
}
export type BigcommerceConfig = Partial<CommerceConfig>

View File

@ -1,6 +1,6 @@
import { createContext, useContext, FC } from 'react'
import useSWR, { responseInterface } from 'swr'
import { useCommerce } from '.'
import { useCommerce } from '..'
export type CartResponse<C> = responseInterface<C, Error> & {
isEmpty: boolean
@ -18,7 +18,8 @@ function getCartCookie() {
}
const CartProvider: FC<CartProviderProps> = ({ children, query, url }) => {
const { fetcher } = useCommerce()
const { fetcher: fetch } = useCommerce()
const fetcher = (url?: string, query?: string) => fetch({ url, query })
const cartId = getCartCookie()
const response = useSWR(() => (cartId ? [url, query] : null), fetcher)

View File

@ -0,0 +1,16 @@
import { Fetcher, useCommerce } from '..'
export default function useAddItem<T, Input>(
fetcher: (fetch: Fetcher<T>, input: Input) => T | Promise<T>
) {
const { fetcher: fetch } = useCommerce()
return async function addItem(input: Input) {
const data = fetcher(fetch, input)
// TODO: Using the state of the cart provider, update the saved cart
// return mutate('/api/cart')
return data
}
}

View File

@ -1,4 +1,11 @@
import { createContext, ReactNode, useContext } from 'react'
import {
createContext,
ReactNode,
useCallback,
useContext,
useMemo,
} from 'react'
import useSWR from 'swr'
const Commerce = createContext<CommerceConfig | null>(null)
@ -12,7 +19,12 @@ export type CommerceConfig = {
locale: string
}
export type Fetcher<T> = (...args: any) => T | Promise<T>
export type Fetcher<T> = (options: FetcherOptions) => T | Promise<T>
export type FetcherOptions = {
url?: string
query?: string
}
export function CommerceProvider({ children, config }: CommerceProps) {
if (!config) {