Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
import Routes from "./routes";
import chakraTheme from "./config/theme";
import { CartProvider } from "./context/cart";
import { CheckoutProvider } from "./context/checkout";

const queryClient = new QueryClient({ defaultOptions: { queries: { refetchOnWindowFocus: false } } });

Expand All @@ -22,7 +23,9 @@ const App = () => {
<ChakraProvider theme={chakraTheme}>
<BrowserRouter>
<CartProvider>
<Routes />
<CheckoutProvider>
<Routes />
</CheckoutProvider>
</CartProvider>
</BrowserRouter>
</ChakraProvider>
Expand Down
28 changes: 28 additions & 0 deletions src/context/checkout/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import React, { useContext, useMemo, useState } from "react";
import { CheckoutResponseDto } from "../../typings/cart";

type ContextType = {
state: CheckoutResponseDto | null;
setState: React.Dispatch<React.SetStateAction<CheckoutResponseDto | null>>
} | null

const CheckoutContext = React.createContext<ContextType>(null)

export const useCheckoutStore = () => {
const context = useContext(CheckoutContext);
if (context === null){
throw new Error("useCheckoutStore must be used within a CheckoutProvider.")
}
return context
}

export const CheckoutProvider: React.FC = ({ children }) => {
const [checkoutState, setCheckoutState] = useState<CheckoutResponseDto | null>(null)

const value = useMemo(() => ({
state: checkoutState,
setState: setCheckoutState
}), [checkoutState])
return <CheckoutContext.Provider value={value}>{children}</CheckoutContext.Provider>

}
19 changes: 10 additions & 9 deletions src/pages/Checkout/Checkout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,14 @@ import CheckoutSkeleton from "./Skeleton";
import StripeForm from "./StripeForm";
import { QueryKeys } from "../../utils/constants/queryKeys";
import { displayPrice } from "../../utils/functions/currency";
import { useCheckoutStore } from "../../context/checkout";

export const Checkout: FC = () => {
// Cart Context Hook.
const cartContext = useCartStore();
const [isLoading, setIsLoading] = useState<boolean>(true);
const { state: cartState, dispatch: cartDispatch } = cartContext;
const [checkoutState, setCheckoutState] = useState<CheckoutResponseDto | null>(null);
const { state: checkoutState, setState: setCheckoutState } = useCheckoutStore()

// For mapping between cart item and info
// const [productInfo, setProductInfo] = useState<ProductInfoMapType>({});
Expand Down Expand Up @@ -72,12 +73,12 @@ export const Checkout: FC = () => {
const subtotal = (product?.price ?? -1) * item.quantity;
return (
<Flex key={item.productId.toString()} mt={[4, 6]}>
<Image
src={product?.images?.[0]}
fallbackSrc="https://via.placeholder.com/100"
<Image
src={product?.images?.[0]}
fallbackSrc="https://via.placeholder.com/100"
boxSize="70"
objectFit="contain"
borderRadius="md"
borderRadius="md"
/>
<Flex flexDirection="column" flex={1} ml={2}>
<Flex justifyContent="space-between" alignItems="flex-start">
Expand Down Expand Up @@ -106,13 +107,13 @@ export const Checkout: FC = () => {
<Divider mt={[4, 8]} mb={[2, 4]} />
<Flex justifyContent="flex-end" mt={2} fontWeight={500} fontSize={["sm", "md", "l"]} gap={2} color="gray.700">
<Flex flexDir="column">
{/*<Text>Subtotal:</Text>*/}
{/*<Text>Discount:</Text>*/}
{/* <Text>Subtotal:</Text> */}
{/* <Text>Discount:</Text> */}
<Text fontSize="lg">Grand total:</Text>
</Flex>
<Flex flexDir="column" textAlign="end">
{/*<Text>{displayPrice(checkoutState?.price?.subtotal ?? 0)}</Text>*/}
{/*<Text>{displayPrice(checkoutState?.price?.discount ?? 0)}</Text>*/}
{/* <Text>{displayPrice(checkoutState?.price?.subtotal ?? 0)}</Text> */}
{/* <Text>{displayPrice(checkoutState?.price?.discount ?? 0)}</Text> */}
<Text fontSize="lg">{displayPrice(checkoutState?.price?.grandTotal ?? 0)}</Text>
</Flex>
</Flex>
Expand Down
8 changes: 6 additions & 2 deletions src/pages/Checkout/StripeForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { CartAction,CartActionType, useCartStore } from "../../context/cart";
import routes from "../../utils/constants/routes";
import { OrderStatusType } from "../../typings/order";
import { api } from "../../services/api";
import { useCheckoutStore } from "../../context/checkout";



Expand All @@ -25,6 +26,9 @@ const PaymentForm = () => {
const { dispatch: cartDispatch, state: cartState } = cartContext;
const [isLoading, setIsLoading] = useState<boolean>(false);
const toast = useToast();

const { state: checkoutState } = useCheckoutStore()

const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
// We don't want to let default form submission happen here,
// which would refresh the page.
Expand Down Expand Up @@ -55,13 +59,13 @@ const PaymentForm = () => {
// TODO: remove userId as we do not have a login
// TODO: order ID to be generated iteratively with api call
setIsLoading(true);
const checkoutCart = await api.postCheckoutCart(cartState.items, cartState.billingEmail, cartState.voucher)

const payload : CartAction = {
type: CartActionType.RESET_CART
}
cartDispatch(payload);
setIsLoading(false);
navigate(`${routes.ORDER_SUMMARY}/${checkoutCart.orderId}`);
navigate(`${routes.ORDER_SUMMARY}/${checkoutState?.orderId}`);
}
};
return (
Expand Down
2 changes: 2 additions & 0 deletions src/typings/cart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ export type CartResponseDto = {
};

export type CheckoutResponseDto = {
orderId: string;
items: [
{
id: string;
Expand All @@ -73,6 +74,7 @@ export type CheckoutResponseDto = {
paymentGateway: string;
clientSecret: string;
};
email: string;
};

export type ProductInfoMapType = Record<string, ProductInfoType>;
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
"@aws-amplify/api-graphql" "2.2.24"
"@aws-amplify/api-rest" "2.0.35"

"@aws-amplify/auth@4.4.4", "@aws-amplify/auth@^4.4.4":
"@aws-amplify/auth@4.4.4":
version "4.4.4"
resolved "https://registry.yarnpkg.com/@aws-amplify/auth/-/auth-4.4.4.tgz#b1c78a3bc0f80bd5303de91bf836eb2b543d2fa0"
integrity sha512-/iQB8teOXxb6XkOK2nPBxldU5YZjMLy6vTpihWMOPP96TWqldgnKSZykYtsrTb6uYK8iF1VWr7DI9OE7UpKONQ==
Expand Down