Commit 95d9b776 authored by Nawasan Wisitsingkhon's avatar Nawasan Wisitsingkhon

add and remove cart in wishlist page

parent 3fa6ee5e
......@@ -74,7 +74,7 @@ export default function Cart() {
message={message.message}
/>
<Paper sx={{ p: 1, overflowX: "scroll" }}>
{wishlist.value.length > 0 ? (
{cart.value.length > 0 ? (
<Table>
<TableHead>
<TableRow>
......
......@@ -9,22 +9,58 @@ import {
TableRow,
} from "@mui/material";
import React, { useContext, useEffect, useState } from "react";
import { UserContext, WishlistContext } from "./_app";
import { CartContext, UserContext, WishlistContext } from "./_app";
import { useRouter } from "next/router";
import axios from "axios";
import { Delete } from "@mui/icons-material";
import { ShoppingCart } from "@mui/icons-material";
import PopupAlert from "@/components/PopupAlert";
import Head from "next/head";
import { RemoveShoppingCart } from "@mui/icons-material";
export default function Wishlist() {
const user = useContext(UserContext);
const wishlist = useContext(WishlistContext);
const cart = useContext(CartContext);
const [products, setProducts] = useState([]);
const [message, setMessage] = useState({ error: false, message: "" });
const router = useRouter();
const [wishlistProduct, setWishlistProduct] = useState([]);
const isInCart = (id) => {
return !!cart.value.filter((ct) => ct.product_id === Number(id)).length;
};
async function onCart(id, isRemove = false) {
if (!user.value?.token) {
setMessage({ message: "คุณยังไม่ได้เข้าสู่ระบบ", error: true });
setTimeout(() => {
setMessage({ message: "", error: true });
}, 2000);
return;
}
if (isRemove) {
let response = await axios.delete(`/api/u/cart?id=${id}`, {
headers: { token: user.value.token },
});
setMessage({ message: "นำออกจากตระกร้าสำเร็จ", error: false });
setTimeout(() => {
setMessage({ message: "", error: false });
}, 2000);
} else {
let response = await axios.post(
"/api/u/cart",
{ id },
{ headers: { token: user.value.token } }
);
setMessage({ message: "เพิ่มลงในตระกร้าสำเร็จ", error: false });
setTimeout(() => {
setMessage({ message: "", error: false });
}, 2000);
}
cart.fetch();
}
const removeFromWishlist = async (id) => {
try {
let response = await axios.delete(`/api/u/wishlist?id=${id}`, {
......@@ -62,7 +98,6 @@ export default function Wishlist() {
}, []);
useEffect(() => {
console.log(wishlist.value);
setWishlistProduct(
wishlist.value.map(
(wish) => products.filter((pd) => pd.id === wish.product_id)[0]
......@@ -129,8 +164,15 @@ export default function Wishlist() {
)}
</TableCell>
<TableCell>
<Button color="warning">
<Button
onClick={() => onCart(pdt.id, isInCart(pdt.id))}
color="warning"
>
{isInCart(pdt.id) ? (
<RemoveShoppingCart />
) : (
<ShoppingCart />
)}
</Button>
</TableCell>
<TableCell>
......
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