From 0483e97954afb47e915f7bec703f193196d19be3 Mon Sep 17 00:00:00 2001 From: Luis Alvarez Date: Tue, 6 Oct 2020 21:00:36 -0500 Subject: [PATCH] Fix cart provider --- components/cart/CartItem/CartItem.tsx | 4 +--- lib/bigcommerce/cart/use-update-item.tsx | 2 +- lib/commerce/cart/index.tsx | 23 +++++++++-------------- 3 files changed, 11 insertions(+), 18 deletions(-) diff --git a/components/cart/CartItem/CartItem.tsx b/components/cart/CartItem/CartItem.tsx index 87da31bd3..daf043d68 100644 --- a/components/cart/CartItem/CartItem.tsx +++ b/components/cart/CartItem/CartItem.tsx @@ -38,13 +38,11 @@ const CartItem = ({ useEffect(() => { // Reset the quantity state if the item quantity changes - if (item.quantity !== quantity) { + if (item.quantity !== Number(quantity)) { setQuantity(item.quantity) } }, [item.quantity]) - console.log('ITEM', item) - return (
  • diff --git a/lib/bigcommerce/cart/use-update-item.tsx b/lib/bigcommerce/cart/use-update-item.tsx index 0dfc30e52..6de709c74 100644 --- a/lib/bigcommerce/cart/use-update-item.tsx +++ b/lib/bigcommerce/cart/use-update-item.tsx @@ -27,7 +27,7 @@ export default function useUpdateItem() { const fn = useCartUpdateItem(fetcher) const updateItem: typeof fn = async (input) => { const data = await fn(input) - await mutate(data) + await mutate(data, false) return data } diff --git a/lib/commerce/cart/index.tsx b/lib/commerce/cart/index.tsx index 09bb0c419..1ca04d871 100644 --- a/lib/commerce/cart/index.tsx +++ b/lib/commerce/cart/index.tsx @@ -1,4 +1,4 @@ -import { createContext, useContext, FC, useCallback, useMemo } from 'react' +import { FC, createContext, useContext, useMemo } from 'react' import useSWR, { responseInterface } from 'swr' import Cookies from 'js-cookie' import { useCommerce } from '..' @@ -11,28 +11,23 @@ export type CartProviderProps = | { query: string; url?: string } | { query?: string; url: string } -const CartContext = createContext | null>(null) +const CartContext = createContext<{ query?: string; url?: string }>({}) const CartProvider: FC = ({ children, query, url }) => { + const value = useMemo(() => ({ query, url }), [query, url]) + return {children} +} + +function useCart() { const { fetcher: fetch, cartCookie } = useCommerce() const fetcher = (url?: string, query?: string) => fetch({ url, query }) const cartId = Cookies.get(cartCookie) + const { url, query } = useContext(CartContext) const response = useSWR(() => (cartId ? [url, query] : null), fetcher, { revalidateOnFocus: false, }) - return ( - // Avoid destructuring the `response` obj from SWR so we don't trigger the getters - // early, also the result of useSWR is memoized and it's better to keep it that way - // so we don't re-render every consumer - - {children} - - ) -} - -function useCart() { - return useContext(CartContext) as CartResponse + return Object.assign(response, { isEmpty: true }) as CartResponse } export { CartProvider, useCart }