import React, { useContext, useEffect, useReducer } from "react"; import Axios from "axios"; import { Helmet } from "react-helmet-async"; import CheckoutSteps from "../components/CheckoutSteps"; import Row from "react-bootstrap/Row"; import Col from "react-bootstrap/Col"; import Card from "react-bootstrap/Card"; import Button from "react-bootstrap/Button"; import ListGroup from "react-bootstrap/ListGroup"; import { getError } from "../components/utils"; import { toast } from "react-toastify"; import { Store } from "../Store"; import { Link, useNavigate } from "react-router-dom"; import LoadingBox from "../components/LoadingBox"; const reducer = (state, action) => { switch (action.type) { case "CREATE_REQUEST": return { ...state, loading: true }; case "CREATE_SUCCESS": return { ...state, loading: false }; case "CREATE_FAIL": return { ...state, loading: false }; default: return state; } }; function PlaceOrderScreen() { const navigate = useNavigate(); const [{ loading }, dispatch] = useReducer(reducer, { loading: false, }); const { state, dispatch: ctxDispatch } = useContext(Store); const { cart, userInfo } = state; const round2 = (num) => Math.round(num * 100 + Number.EPSILON) / 100; cart.itemsPrice = round2( cart.cartItems.reduce((a, c) => a + c.quantity * c.price, 0) ); cart.shippingPrice = cart.itemsPrice > 1500 ? round2(0) : round2(150); cart.totalPrice = cart.itemsPrice + cart.shippingPrice; const paymentHandler = async () => { navigate(`/placeorder/payment`); }; const placeOrderHandler = async () => { try { dispatch({ type: "CREATE_REQUEST" }); const { data } = await Axios.post( "/api/orders", { orderItems: cart.cartItems, shippingAddress: cart.shippingAddress, paymentMethod: cart.paymentMethod, itemsPrice: cart.itemsPrice, shippingPrice: cart.shippingPrice, totalPrice: cart.totalPrice, }, { headers: { authorization: `Bearer ${userInfo.token}`, }, } ); ctxDispatch({ type: "CART_CLEAR" }); dispatch({ type: "CREATE_SUCCESS" }); localStorage.removeItem("cartItems"); navigate(`/order/${data.order._id}`); } catch (err) { dispatch({ type: "CREATE_FAIL" }); toast.error(getError(err)); } }; useEffect(() => { if (!cart.paymentMethod) { navigate("/payment"); } }, [cart, navigate]); return (