Commit 3fa6ee5e authored by Nawasan Wisitsingkhon's avatar Nawasan Wisitsingkhon

remove from cart in index

parent eb6f7e3a
...@@ -49,6 +49,29 @@ const CartController = { ...@@ -49,6 +49,29 @@ const CartController = {
res.json({ status: 200, message: "found some error on server" }); res.json({ status: 200, message: "found some error on server" });
} }
}, },
/**
*
* @param {Request} req
* @param {Response} res
*/
async delete(req, res) {
try {
const { id } = req.query;
if (!id) throw 400;
let check_cart = await db.cart.findFirst({
where: {
AND: { user_id: Number(req.user.id), product_id: Number(id) },
},
});
if (!check_cart) throw 400;
await db.cart.delete({ where: { id: check_cart.id } });
await db.$disconnect();
res.json({ status: 401, message: "remove success" });
} catch (err) {
console.log(err);
res.json({ status: 400, message: "remove failed with error on server" });
}
},
}; };
export default CartController; export default CartController;
...@@ -9,5 +9,6 @@ UserRouter.delete("/wishlist", WishlistController.delete); ...@@ -9,5 +9,6 @@ UserRouter.delete("/wishlist", WishlistController.delete);
UserRouter.get("/cart", CartController.index); UserRouter.get("/cart", CartController.index);
UserRouter.post("/cart", CartController.create); UserRouter.post("/cart", CartController.create);
UserRouter.delete("/cart", CartController.delete);
export default UserRouter; export default UserRouter;
...@@ -21,10 +21,12 @@ import { headers } from "../../next.config"; ...@@ -21,10 +21,12 @@ import { headers } from "../../next.config";
export default function ProductCard({ export default function ProductCard({
product, product,
isFav, isFav,
isCart,
favHandler, favHandler,
cartHandler, cartHandler,
}) { }) {
const fav = isFav; const fav = isFav;
const cart = isCart;
/** /**
* *
...@@ -73,8 +75,12 @@ export default function ProductCard({ ...@@ -73,8 +75,12 @@ export default function ProductCard({
> >
{fav ? <Favorite /> : <FavoriteBorder />} {fav ? <Favorite /> : <FavoriteBorder />}
</Button> </Button>
<Button title="เพิ่มลงตระกร้า" color="warning" onClick={cartHandler}> <Button
<ShoppingCart /> title={cart ? "นำออกจากตระกร้า" : "เพิ่มลงในตระกร้า"}
color="warning"
onClick={cartHandler}
>
{cart ? <RemoveShoppingCart /> : <ShoppingCart />}
</Button> </Button>
</span> </span>
{Number(product.discount) > 0 ? ( {Number(product.discount) > 0 ? (
......
...@@ -26,7 +26,23 @@ export default function Cart() { ...@@ -26,7 +26,23 @@ export default function Cart() {
const router = useRouter(); const router = useRouter();
const [CartProduct, setCartProduct] = useState([]); const [CartProduct, setCartProduct] = useState([]);
const removeFromCart = async (id) => {}; const removeFromCart = async (id) => {
let response = await axios.delete(`/api/u/cart?id=${id}`, {
headers: { token: user.value.token },
});
if (response.data.status === 401) {
cart.fetch();
setMessage({ message: "นำออกจากตระกร้าสำเร็จ", error: false });
setTimeout(() => {
setMessage({ message: "", error: false });
}, 2000);
} else {
setMessage({ message: "พบข้อผิดพลาดกรุณาลองใหม่อีกครั้ง", error: true });
setTimeout(() => {
setMessage({ message: "", error: true });
}, 2000);
}
};
const fetchProduct = async () => { const fetchProduct = async () => {
try { try {
let product = await axios.get("/api/product"); let product = await axios.get("/api/product");
......
...@@ -4,7 +4,7 @@ import Head from "next/head"; ...@@ -4,7 +4,7 @@ import Head from "next/head";
import { useContext, useEffect, useState } from "react"; import { useContext, useEffect, useState } from "react";
import ProductCard from "@/components/ProductCard"; import ProductCard from "@/components/ProductCard";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { UserContext, WishlistContext } from "./_app"; import { CartContext, UserContext, WishlistContext } from "./_app";
import PopupAlert from "@/components/PopupAlert"; import PopupAlert from "@/components/PopupAlert";
const inter = Inter({ subsets: ["latin"] }); const inter = Inter({ subsets: ["latin"] });
...@@ -15,6 +15,7 @@ export default function Home() { ...@@ -15,6 +15,7 @@ export default function Home() {
const [products, setProducts] = useState([]); const [products, setProducts] = useState([]);
const [message, setMessage] = useState({ message: "", error: false }); const [message, setMessage] = useState({ message: "", error: false });
const wishlist = useContext(WishlistContext); const wishlist = useContext(WishlistContext);
const cart = useContext(CartContext);
const productsFilter = !!router.query?.q const productsFilter = !!router.query?.q
? products.filter((prod) => String(prod.name).includes(router.query.q)) ? products.filter((prod) => String(prod.name).includes(router.query.q))
...@@ -29,14 +30,18 @@ export default function Home() { ...@@ -29,14 +30,18 @@ export default function Home() {
return; return;
} }
if (isRemove) { if (isRemove) {
let response = await axios.delete(`/api/u/cart?id=${id}`, {
headers: { token: user.value.token },
});
} else { } else {
let response = await axios.post( let response = await axios.post(
"/api/u/cart", "/api/u/cart",
{ id }, { id },
{ headers: { token: user.value.token } } { headers: { token: user.value.token } }
); );
console.log(response.data);
} }
cart.fetch();
} }
async function onWishlist(id, isRemove = false) { async function onWishlist(id, isRemove = false) {
...@@ -51,7 +56,6 @@ export default function Home() { ...@@ -51,7 +56,6 @@ export default function Home() {
let response = await axios.delete(`/api/u/wishlist?id=${id}`, { let response = await axios.delete(`/api/u/wishlist?id=${id}`, {
headers: { token: user.value.token }, headers: { token: user.value.token },
}); });
console.log(response.data);
} else { } else {
let response = await axios.post( let response = await axios.post(
"/api/u/wishlist", "/api/u/wishlist",
...@@ -98,8 +102,18 @@ export default function Home() { ...@@ -98,8 +102,18 @@ export default function Home() {
(wish) => wish.product_id === Number(prod.id) (wish) => wish.product_id === Number(prod.id)
).length ).length
} }
isCart={
!!cart.value.filter((ct) => ct.product_id === Number(prod.id))
.length
}
product={prod} product={prod}
cartHandler={() => onCart(prod.id)} cartHandler={() =>
onCart(
prod.id,
!!cart.value.filter((ct) => ct.product_id === Number(prod.id))
.length
)
}
favHandler={() => favHandler={() =>
onWishlist( onWishlist(
prod.id, prod.id,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment