Skip to content

Commit

Permalink
fix cart only working after reload on new browser visits
Browse files Browse the repository at this point in the history
  • Loading branch information
yinkakun committed Oct 24, 2022
1 parent 29523fe commit df03141
Showing 1 changed file with 33 additions and 25 deletions.
58 changes: 33 additions & 25 deletions storefront/context/cart-context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const initialCartState: CartState = null;

interface CartContext {
cart: CartState;
cartId: string;
setCart: React.Dispatch<React.SetStateAction<CartState>>;
}

Expand All @@ -20,53 +21,57 @@ interface CartProviderProps {
const CART_ID = 'cart_id';
const isBrowser = typeof window !== 'undefined';

const cartId = isBrowser ? localStorage.getItem(CART_ID) : null;

export const CartProvider = ({ children }: CartProviderProps) => {
const [cartIsInit, setCartIsInit] = useState(false);
const [cart, setCart] = useState<CartState>(initialCartState);
const [cartId, setCartId] = useState<string>('');

useEffect(() => {
if (cartIsInit) return;
const cartId = isBrowser && window.localStorage.getItem(CART_ID);

const initializeCart = async () => {
const cartId = isBrowser && window.localStorage.getItem(CART_ID);

const setCartId = (cartId: string) => {
if (isBrowser) {
window.localStorage.setItem(CART_ID, cartId);
}
};
const saveCartId = (cartId: string) => {
if (isBrowser) {
window.localStorage.setItem(CART_ID, cartId);
setCartId(cartId);
}
};

const createNewCart = async () => {
const DEFAULT_REGION_ID = await (
await medusaClient.regions.list()
).regions[0].id;

if (!cartId) {
const { cart } = await medusaClient.carts.create({
region_id: DEFAULT_REGION_ID,
});
const { cart } = await medusaClient.carts.create({
region_id: DEFAULT_REGION_ID,
});

if (!cart || cart.completed_at) {
setCartId('');
setCart(initialCartState);
}
setCartId(cart.id);
setCart(cart);
saveCartId(cart.id);
setCart(cart);
};

const initializeCart = async () => {
if (!cartId) {
createNewCart();
}

if (cartId) {
const { cart } = await medusaClient.carts.retrieve(cartId);
setCart((prev) => ({ ...prev, ...cart }));

if (!cart || cart.completed_at) {
createNewCart();
}

setCart(cart);
}
};

initializeCart();
setCartIsInit(true);
}, [cart, setCart, cartIsInit, setCartIsInit]);
}, [cart, setCart, cartIsInit]);

return (
<CartContext.Provider value={{ cart, setCart }}>
<CartContext.Provider value={{ cart, setCart, cartId }}>
{children}
</CartContext.Provider>
);
Expand All @@ -91,15 +96,17 @@ export const useCart = () => {
throw new Error('useCart must be used within a CartProvider');
}

const { cart, setCart } = context;
const { cart, setCart, cartId } = context;

const addItem = async ({
variantId,
quantity,
onError,
onSuccess,
}: AddItemParams) => {
if (!cartId) return;
if (!cartId) {
throw new Error('No cart id found');
}

try {
const { cart } = await medusaClient.carts.lineItems.create(cartId, {
Expand All @@ -109,6 +116,7 @@ export const useCart = () => {
setCart(cart);
onSuccess && onSuccess();
} catch (error) {
console.log(error);
onError && onError();
}
};
Expand Down

1 comment on commit df03141

@vercel
Copy link

@vercel vercel bot commented on df03141 Oct 24, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.