Commit 92932730 authored by Nawasan Wisitsingkhon's avatar Nawasan Wisitsingkhon

show fav count in navbar

parent 097cb3fe
......@@ -14,7 +14,7 @@ import MenuIcon from "@mui/icons-material/Menu";
import SearchIcon from "@mui/icons-material/Search";
import AccountCircle from "@mui/icons-material/AccountCircle";
import ShoppingCart from "@mui/icons-material/ShoppingCart";
import { UserContext } from "@/pages/_app";
import { UserContext, WishlistContext } from "@/pages/_app";
import Link from "next/link";
import { Favorite } from "@mui/icons-material";
import { Logout, SupervisedUserCircle } from "@mui/icons-material";
......@@ -63,12 +63,12 @@ const StyledInputBase = styled(InputBase)(({ theme }) => ({
function Navbar(props) {
const router = useRouter();
const [search, setSearch] = React.useState(router.query?.q ?? "");
const wishlist = useContext(WishlistContext);
const user = useContext(UserContext);
const { window } = props;
const [anchorEl, setAnchorEl] = React.useState(null);
const [mobileMoreAnchorEl, setMobileMoreAnchorEl] = React.useState(null);
const [mobileOpen, setMobileOpen] = React.useState(false);
const isMenuOpen = Boolean(anchorEl);
const isMobileMenuOpen = Boolean(mobileMoreAnchorEl);
......@@ -124,7 +124,7 @@ function Navbar(props) {
aria-label="show 4 new mails"
color="inherit"
>
<Badge badgeContent={4} color="error">
<Badge badgeContent={wishlist.value.length} color="error">
<Favorite />
</Badge>
</IconButton>
......
import React from "react";
import { Snackbar, Alert } from "@mui/material";
export default function PopupAlert({
open = false,
message = "",
isError = false,
}) {
return (
<Snackbar
anchorOrigin={{ horizontal: "center", vertical: "top" }}
open={open}
>
<Alert severity={isError ? "error" : "success"}>{message}</Alert>
</Snackbar>
);
}
......@@ -9,14 +9,24 @@ import userCookie from "@/components/lib/userCookie";
import AdminLayout from "@/components/layout/AdminLayout";
import { usePathname } from "next/navigation";
import Error from "./_error";
import axios from "axios";
// axios.defaults.baseURL = ""
export const UserContext = createContext(null);
export const WishlistContext = createContext(null);
export default function App({ Component, pageProps }) {
const [user, setUser] = useState({});
const [wishlist, setWishlist] = useState([]);
const pathname = usePathname();
const fetchWishlist = async () => {
if (!user?.token) return;
let response = await axios.get("/api/u/wishlist", {
headers: { token: user.token },
});
setWishlist(response.data.wishlists);
};
useEffect(() => {
const usrcookie = new userCookie();
let token = usrcookie.token.split(".")[1];
......@@ -29,25 +39,31 @@ export default function App({ Component, pageProps }) {
}
}, []);
useEffect(() => {
fetchWishlist();
}, [user]);
return (
<UserContext.Provider value={{ value: user, set: setUser }}>
{pathname.split("/")[1] === "admin" ? (
<>
{user.rank ? (
<AdminLayout>
<Component {...pageProps} />
</AdminLayout>
) : (
<UserLayout>
<Error />
</UserLayout>
)}
</>
) : (
<UserLayout>
<Component {...pageProps} />
</UserLayout>
)}
<WishlistContext.Provider value={{ value: wishlist, set: setWishlist }}>
{pathname.split("/")[1] === "admin" ? (
<>
{user.rank ? (
<AdminLayout>
<Component {...pageProps} />
</AdminLayout>
) : (
<UserLayout>
<Error />
</UserLayout>
)}
</>
) : (
<UserLayout>
<Component {...pageProps} />
</UserLayout>
)}
</WishlistContext.Provider>
</UserContext.Provider>
);
}
......@@ -4,7 +4,8 @@ import Head from "next/head";
import { useContext, useEffect, useState } from "react";
import ProductCard from "@/components/ProductCard";
import { useRouter } from "next/router";
import { UserContext } from "./_app";
import { UserContext, WishlistContext } from "./_app";
import PopupAlert from "@/components/PopupAlert";
const inter = Inter({ subsets: ["latin"] });
......@@ -12,13 +13,21 @@ export default function Home() {
const user = useContext(UserContext);
const router = useRouter();
const [products, setProducts] = useState([]);
const [myWishlisth, setMywishlist] = useState([]);
const [message, setMessage] = useState({ message: "", error: false });
const wishlist = useContext(WishlistContext);
const productsFilter = !!router.query?.q
? products.filter((prod) => String(prod.name).includes(router.query.q))
: products.filter((prod) => Number(prod.stock) > 0);
async function onWishlist(id, isRemove = false) {
if (!user.value?.token) {
setMessage({ message: "คุณยังไม่ได้เข้าสู่ระบบ", error: true });
setTimeout(() => {
setMessage({ message: "", error: false });
}, 2000);
return;
}
if (isRemove) {
} else {
let response = await axios.post(
......@@ -28,7 +37,7 @@ export default function Home() {
);
console.log(response.data);
}
FetchWishlist()
FetchWishlist();
}
const FetchProduct = async () => {
......@@ -41,28 +50,29 @@ export default function Home() {
let response = await axios.get("/api/u/wishlist", {
headers: { token: user.value.token },
});
setMywishlist(response.data.wishlists);
wishlist.set(response.data.wishlists);
};
useEffect(() => {
FetchProduct();
FetchWishlist();
console.log(myWishlisth);
console.log();
}, [user]);
return (
<>
<Head>
<title>OpenShop</title>
</Head>
<PopupAlert
open={!!message.message.length}
isError={message.error}
message={message.message}
/>
<div>
<div className="mx-auto text-left grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 2xl:grid-cols-4 max-w-[1520px]">
{productsFilter.map((prod, idx) => (
<ProductCard
key={idx}
isFav={
!!myWishlisth.filter(
!!wishlist.value.filter(
(wish) => wish.product_id === Number(prod.id)
).length
}
......@@ -70,7 +80,7 @@ export default function Home() {
favHandler={() =>
onWishlist(
prod.id,
!!myWishlisth.filter(
!!wishlist.value.filter(
(wish) => wish.product_id === Number(prod.id)
).length
)
......
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