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