You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

115 lines
3.5 KiB
JavaScript

import "nes.css/css/nes.min.css";
import { useState, useContext } from 'react';
import { Button, Modal } from 'react-bootstrap';
import UserContext from "../UserContext.js";
import Swal from "sweetalert2";
const AddToCartModal = ({ productId, addToCart }) => {
const { user } = useContext(UserContext);
const [quantity, setQuantity] = useState(1);
const [isOpen, setIsOpen] = useState(false);
const openModal = () => {
setIsOpen(true);
}
const closeModal = () => {
setIsOpen(false);
}
const decrementQuantity = () => {
if (quantity > 1) {
setQuantity(quantity - 1);
}
};
const incrementQuantity = () => {
setQuantity(quantity + 1);
};
const AddtoCart = () => {
if (!user || user.isAdmin == null) {
Swal.fire({
title: "Authentication error",
icon: "error",
text: "Please log in to add to cart."
});
return;
} else if (user.isAdmin) {
Swal.fire({
title: "Action forbidden",
icon: "error",
text: "Only non-admin users can add to cart."
})
return;
}
fetch(`${process.env.REACT_APP_API_BASE_URL}/products/add-to-cart`, {
method : "POST",
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
"Content-Type" : "application/json"
},
body: JSON.stringify({
productId: productId,
quantity: quantity
})
}).then(result => result.json())
.then(data => {
if (data) {
Swal.fire({
title: "Add to cart succesful!",
icon: "success",
text: "Product successfully added to cart."
})
closeModal();
setQuantity(0);
}else{
Swal.fire({
title: "Something went wrong",
icon: "error",
text: "Please try again"
})
}
})
}
return (
<>
<Button className="nes-btn btn-submit" onClick = {() => openModal()}>Add to Cart</Button>
<Modal show = {isOpen} >
<Modal.Header onClick = {closeModal} closeButton>
<Modal.Title>Add to Cart</Modal.Title>
</Modal.Header>
<Modal.Body>
<p className="text-center fs-1">Quantity:</p>
<div className="d-grid d-flex gap-4 justify-content-center">
<Button className="nes-btn is-error" onClick={decrementQuantity}>-</Button>
<span className="fs-1">{quantity}</span>
<Button className="nes-btn is-success" onClick={incrementQuantity}>+</Button>
</div>
</Modal.Body>
<Modal.Footer>
<Button className="nes-btn fs-5 is-primary" onClick = {() => AddtoCart()} >Add to Cart</Button>
</Modal.Footer>
</Modal>
</>
);
};
export default AddToCartModal;