Skip to content

Commit

Permalink
add toast-bar and loading state to add-to-cart button
Browse files Browse the repository at this point in the history
  • Loading branch information
yinkakun committed Oct 23, 2022
1 parent 1127d29 commit 24d871a
Show file tree
Hide file tree
Showing 6 changed files with 73 additions and 7 deletions.
16 changes: 14 additions & 2 deletions storefront/context/cart-context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ export const CartProvider = ({ children }: CartProviderProps) => {
interface AddItemParams {
variantId: string;
quantity: number;
onError?: () => void;
onSuccess?: () => void;
}

interface UpdateItemParams {
Expand All @@ -91,13 +93,23 @@ export const useCart = () => {

const { cart, setCart } = context;

const addItem = async ({ variantId, quantity }: AddItemParams) => {
if (cartId) {
const addItem = async ({
variantId,
quantity,
onError,
onSuccess,
}: AddItemParams) => {
if (!cartId) return;

try {
const { cart } = await medusaClient.carts.lineItems.create(cartId, {
variant_id: variantId,
quantity,
});
setCart(cart);
onSuccess && onSuccess();
} catch (error) {
onError && onError();
}
};

Expand Down
1 change: 1 addition & 0 deletions storefront/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"react-dom": "18.2.0",
"react-feather": "2.0.10",
"react-hook-form": "7.38.0",
"react-hot-toast": "2.4.0",
"sharp": "0.31.1",
"tailwindcss": "3.1.8"
},
Expand Down
2 changes: 2 additions & 0 deletions storefront/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { DefaultSeo } from 'next-seo';
import { CartProvider } from '@/context/cart-context';
import { LenisProvider } from '@/context/lenis-context';

import { Toaster } from 'react-hot-toast';
import { AnimatePresence } from 'framer-motion';

export default function MyApp({ Component, pageProps }: AppProps) {
Expand All @@ -16,6 +17,7 @@ export default function MyApp({ Component, pageProps }: AppProps) {
<DefaultSeo titleTemplate="%s | Monster" defaultTitle="Monster" />
<LenisProvider>
<CartProvider>
<Toaster position="bottom-right" />
<AnimatePresence mode="wait">
<Component {...pageProps} />
</AnimatePresence>
Expand Down
21 changes: 16 additions & 5 deletions storefront/pages/shop/[handle].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,38 @@ import { medusaClient } from '@/lib/medusa-client';
import { GetStaticPropsContext, InferGetStaticPropsType } from 'next';
import { Layout } from '@/components/layout';
import { Container } from '@/components/layout/container';
import React from 'react';
import { useState } from 'react';
import { Minus, Plus } from 'react-feather';
import { formatPrice } from '@/utils/format-price';
import { useCart } from '@/context/cart-context';
import { errorToast, successToast } from '@/utils/toasts';

type ProductPageProps = InferGetStaticPropsType<typeof getStaticProps>;

const ProductPage = ({ product }: ProductPageProps) => {
const [quantity, setQuantity] = React.useState(1);
const [quantity, setQuantity] = useState(1);
const { addItem } = useCart();
const { title, thumbnail, description, variants } = product!;
const price = variants[0].prices[0];
const variantId = variants[0].id;

const [isLoading, setIsLoading] = useState(false);

const handleAddToCart = () => {
setIsLoading(true);
addItem({
variantId: variantId,
quantity,
onSuccess: () => {
setQuantity(1);
setIsLoading(false);
successToast('Item successfully added to cart');
},
onError: () => {
setIsLoading(false);
errorToast('Error Adding item to item to cart');
},
});

setQuantity(1);
};

return (
Expand Down Expand Up @@ -53,7 +64,7 @@ const ProductPage = ({ product }: ProductPageProps) => {
onClick={handleAddToCart}
className="w-full bg-monster-green p-3 py-2 font-alt-sans text-lg uppercase text-noir duration-500 hover:bg-monster-green-300 md:max-w-sm"
>
Add to cart
{isLoading ? 'Adding...' : 'Add to cart'}
</button>
</div>
<p className="font-alt-sans text-sm font-light text-lotion text-opacity-90">
Expand Down
28 changes: 28 additions & 0 deletions storefront/utils/toasts.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import toast from 'react-hot-toast';
import { CheckCircle, X } from 'react-feather';

export const successToast = (message: string) => {
toast.custom((toast) => (
<div
className={`mb-2 flex items-center gap-3 bg-green-500 px-8 py-3 font-alt-sans text-xs uppercase text-white ${
toast.visible ? 'animate-enter' : 'animate-leave'
}`}
>
<span>{message}</span>
<CheckCircle size={20} />
</div>
));
};

export const errorToast = (message: string) => {
toast.custom((toast) => (
<div
className={`mb-2 flex items-center gap-3 bg-red-500 px-6 py-3 font-alt-sans text-xs uppercase text-white ${
toast.visible ? 'animate-enter' : 'animate-leave'
}`}
>
<span>{message}</span>
<X size={18} />
</div>
));
};
12 changes: 12 additions & 0 deletions storefront/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2910,6 +2910,11 @@ globrex@^0.1.2:
resolved "https://registry.yarnpkg.com/globrex/-/globrex-0.1.2.tgz#dd5d9ec826232730cd6793a5e33a9302985e6098"
integrity sha512-uHJgbwAMwNFf5mLst7IWLNg14x1CkeqglJb/K3doi4dw6q2IvAAmM/Y81kevy83wP+Sst+nutFTYOGg3d1lsxg==

goober@^2.1.10:
version "2.1.11"
resolved "https://registry.yarnpkg.com/goober/-/goober-2.1.11.tgz#bbd71f90d2df725397340f808dbe7acc3118e610"
integrity sha512-5SS2lmxbhqH0u9ABEWq7WPU69a4i2pYcHeCxqaNq6Cw3mnrF0ghWNM4tEGid4dKy8XNIAUbuThuozDHHKJVh3A==

graceful-fs@^4.1.2, graceful-fs@^4.1.6, graceful-fs@^4.2.0, graceful-fs@^4.2.4, graceful-fs@^4.2.6:
version "4.2.10"
resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.10.tgz#147d3a006da4ca3ce14728c7aefc287c367d7a6c"
Expand Down Expand Up @@ -4840,6 +4845,13 @@ [email protected]:
resolved "https://registry.yarnpkg.com/react-hook-form/-/react-hook-form-7.38.0.tgz#53d6a68df587ce4ce88352f63e0ecc7fc8779320"
integrity sha512-gxWW1kMeru9xR1GoR+Iw4hA+JBOM3SHfr4DWCUKY0xc7Vv1MLsF109oHtBeWl9shcyPFx67KHru44DheN0XY5A==

[email protected]:
version "2.4.0"
resolved "https://registry.yarnpkg.com/react-hot-toast/-/react-hot-toast-2.4.0.tgz#b91e7a4c1b6e3068fc599d3d83b4fb48668ae51d"
integrity sha512-qnnVbXropKuwUpriVVosgo8QrB+IaPJCpL8oBI6Ov84uvHZ5QQcTp2qg6ku2wNfgJl6rlQXJIQU5q+5lmPOutA==
dependencies:
goober "^2.1.10"

react-is@^16.13.1:
version "16.13.1"
resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.13.1.tgz#789729a4dc36de2999dc156dd6c1d9c18cea56a4"
Expand Down

1 comment on commit 24d871a

@vercel
Copy link

@vercel vercel bot commented on 24d871a Oct 23, 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.