import React, { useContext, useEffect, useReducer, useState } from "react"; import Container from "react-bootstrap/Container"; import { Helmet } from "react-helmet-async"; import Form from "react-bootstrap/Form"; import Button from "react-bootstrap/Button"; import { useNavigate, useParams } from "react-router-dom"; import { Store } from "../Store"; import axios from "axios"; import { getError } from "../components/utils"; import { toast } from "react-toastify"; 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 CardPaymentScreen() { const [validated, setValidated] = useState(false); 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 (event) => { event.preventDefault(); const form = event.currentTarget; if (form.checkValidity() === false) { event.preventDefault(); event.stopPropagation(); } setValidated(true); if (form.checkValidity() === true) { 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, isPaid: true, paidAt: Date.now(), }, { 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)); } } }; return (
Плати нарачка
Име и Презиме setHolderName(e.target.value)} required > Број на картичка setCardNumber(e.target.value)} required > CVV2/CVC2 setCvv(e.target.value)} required > Рок на важност
); } export default CardPaymentScreen;