Skip to content

Commit

Permalink
wishlist page made dynamic
Browse files Browse the repository at this point in the history
  • Loading branch information
ShivanshPlays committed Oct 26, 2024
1 parent bd555d9 commit d8ca637
Show file tree
Hide file tree
Showing 14 changed files with 312 additions and 163 deletions.
8 changes: 7 additions & 1 deletion actions/get-products.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ interface GetProductsParams {

export default async function getProducts(
params: GetProductsParams,
storeId: string
storeId: string,
userId?:string
) {
const { isFeatured, categoryId, productName } = params;

Expand All @@ -75,6 +76,11 @@ export default async function getProducts(
seller: { select: { storeName: true } },
category: { select: { name: true } },
images: true,
wishlists:userId?{
where:{
userId: userId?userId:undefined
}
}:undefined
},
});
// console.log(products);
Expand Down
105 changes: 79 additions & 26 deletions actions/wishlist-actions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,84 @@
import prismadb from "@/lib/prismadb";
import { Prisma } from "@prisma/client"; // Import Prisma for error handling

export async function WishlistPost(data: FormData): Promise<{ success: boolean; error?: string }> {
const productId = data.get("productid") as string;
const userId = data.get("userid") as string;

try {
const res = await prismadb.wishlist.create({
data: {
userId: userId,
productId: productId,
},
});

console.log(res);
return { success: true }; // Return success if the entry was created
} catch (err) {
if (err instanceof Prisma.PrismaClientKnownRequestError) {
// Check if the error code is P2002 (Unique constraint failed)
if (err.code === "P2002") {
console.log("Duplicate entry detected:", err.message);
return { success: false, error: "This item is already in your wishlist." }; // Customize your error message here
}
}

// Log the error for any other type of error
console.log(err);
return { success: false, error: "An unexpected error occurred." }; // General error message
export async function WishlistPost(
data: FormData
): Promise<{ success: boolean; error?: string }> {
const productId = data.get("productid") as string;
const userId = data.get("userid") as string;

try {
const res = await prismadb.wishlist.create({
data: {
userId: userId,
productId: productId,
},
});

console.log(res);
return { success: true }; // Return success if the entry was created
} catch (err) {
if (err instanceof Prisma.PrismaClientKnownRequestError) {
// Check if the error code is P2002 (Unique constraint failed)
if (err.code === "P2002") {
console.log("Duplicate entry detected:", err.message);
return {
success: false,
error: "This item is already in your wishlist.",
}; // Customize your error message here
}
}

// Log the error for any other type of error
console.log(err);
return { success: false, error: "An unexpected error occurred." }; // General error message
}
}

export async function WishlistGetByUser(
userId: string
): Promise<{ success: boolean; data?: any; error?: string }> {
try {
const res = await prismadb.wishlist.findMany({
where: {
userId,
},
include: {
product: {
include: {
images: true,
},
},
},
});

// console.log(res);
return { success: true, data: res }; // Include success and return the data
} catch (err) {
console.log(err);

return { success: false, error: "An unexpected error occurred." };
}
}



export async function WishlistSpecificEntry(
userId:string
,productId:string): Promise<{ success: boolean; error?: string }> {

const res=await prismadb.wishlist.findUnique({
where:{
userId_productId:{
userId,
productId
}
}
})

console.log(res);

return {success:true}


}
21 changes: 11 additions & 10 deletions app/(Customer)/WishList/components/wishlistItem.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
import { Button } from "@/components/ui/button";
import Image from "next/image";
import { productWithImages } from "../page";

interface wishlistItemProps{
item:{
id:number,
price:string,
name:string,
image:string
}
item:productWithImages
Id:string,
onRemove: (id: string) => void;
}
// WishlistItem.js
const WishlistItem:React.FC<wishlistItemProps> = ({ item }) => {
const WishlistItem:React.FC<wishlistItemProps> = ({ item, }) => {


// console.log(item);
return (
<div className="border dark:border-gray-200 max-w-[400px] p-4 rounded-lg shadow-md hover:shadow-lg transition">
<Image width={1000} height={1000} src={item.image} alt={item.name} className="w-full h-40 object-cover rounded border-b" />
<div className="border flex items-center justify-center flex-col dark:border-gray-200 max-w-full p-4 rounded-lg shadow-md hover:shadow-lg transition">
<Image width={1000} height={1000} src={item.images[0].url} alt={item.name} className="w-full h-full object-cover rounded border-b" />
<h2 className="mt-2 text-xl dark:text-gray-200 font-semibold">{item.name}</h2>
<p className="text-lg text-gray-600">{item.price}</p>
<div className="mt-4 flex justify-between">
<div className="mt-4 flex justify-between gap-2">
<Button variant="outline" className="dark:text-gray-200 dark:hover:bg-[#f8f8f8] dark:hover:text-gray-700">Remove</Button>
<Button variant={"default"} className= "bg-customTeal dark:bg-Green dark:text-gray-100 dark:hover:opacity-80">Move to Cart</Button>
</div>
Expand Down
146 changes: 109 additions & 37 deletions app/(Customer)/WishList/page.tsx
Original file line number Diff line number Diff line change
@@ -1,46 +1,118 @@
// Wishlist.js
"use client";
import { Button } from "@/components/ui/button";
import WishlistItem from "./components/wishlistItem";
import { useSession } from "next-auth/react";
import { WishlistGetByUser } from "@/actions/wishlist-actions";
import { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { Image, Product, Wishlist } from "@prisma/client";
// import { useTheme } from "@/context/themeProvider";
import { Spinner } from "@/components/ui/spinner";
import Link from "next/link";

const wishlistItems = [
{
id: 1,
name: "Hybrid Tomato",
price: "29",
image: "/products/tomato.avif",
},
{
id: 2,
name: "Hen Fruit White Protein Rich Eggs",
price: "92",
image: "/products/eggs.avif",
},
];

const Wishlist = () => {
// const wishlistItems = [
// {
// id: 1,
// name: "Hybrid Tomato",
// price: "29",
// image: "/products/tomato.avif",
// },
// {
// id: 2,
// name: "Hen Fruit White Protein Rich Eggs",
// price: "92",
// image: "/products/eggs.avif",
// },
// ];

export interface productWithImages extends Product {
images: Image[];
}
interface wishlistProps extends Wishlist {
product: productWithImages;
}
const WishlistPage = () => {
const session = useSession();
const userId = session.data?.user.id;

// const { theme } = useTheme() || { theme: "light" }; // Get the current theme and toggle function

const [wishlistItems, setWishlistItems] = useState<wishlistProps[]>([]);

const [loading, setLoading] = useState(false);

// console.log(wishlistItems);


useEffect(() => {
const getItems = async () => {
const response = await WishlistGetByUser(userId||"");
if (response.success) {
setWishlistItems(response.data);
} else {
toast.error("error fetching wishlist");
}
setLoading(false);
};
getItems();
}, [userId]);

// if (!userId) {
// // openDialog();

// return (
// <FlashAlert
// modalLogo={
// <LogIn
// className={`h-16 w-16 ${
// theme === "light" ? "text-customTeal" : "text-Green"
// } mx-auto`}
// />
// }
// modalTitle={"User not logged in"}
// modalDescription={"Please login to access your wishlist"}
// />
// );
// }

const handleRemove = (id: string) => {
setWishlistItems((prevItems) => prevItems.filter((item) => item.id !== id));
};

if (loading) {
return <Spinner />;
}

// console.log(wishlistItems+"dakjnjkanefnj")
return (
<div className="h-full dark:bg-DarkGray pb-10">
<div className="text-white flex items-center justify-center bg-customTeal dark:bg-gradient-to-r from-Green to-Yellow h-full mb-20 p-24">
<div className="text-4xl pt-5 lg:pt-0 lg:text-7xl text-center text-gray-200 lg:text-start font-extrabold font-handlee">
Wish List
</div>
</div>
<div className="mt-5 flex items-center justify-center">
{wishlistItems.length > 0 ? (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-10">
{wishlistItems.map((item) => (
<WishlistItem key={item.id} item={item} />
))}
</div>
) : (
<div className="text-center text-gray-700 dark:text-gray-500">
<p>Your wishlist is empty!</p>
<Button className="bg-customTeal dark:text-gray-100 dark:hover:opacity-80 dark:bg-Green mt-4">Continue Shopping</Button>
<>
<div className="h-full dark:bg-DarkGray pb-10">
<div className="text-white flex items-center justify-center bg-customTeal dark:bg-gradient-to-r from-Green to-Yellow h-full mb-20 p-24">
<div className="text-4xl pt-5 lg:pt-0 lg:text-7xl text-center text-gray-200 lg:text-start font-extrabold font-handlee">
Wish List
</div>
)}
</div>
<div className="mt-5 flex items-center justify-center">
{wishlistItems.length > 0 ? (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-10 px-10">
{wishlistItems.map((item) => (
<WishlistItem key={item.id} Id={item.id} item={item.product} onRemove={handleRemove}/>
))}
</div>
) : (
<div className="text-center text-gray-700 dark:text-gray-500">
<p>Your wishlist is empty!</p>
<Link href={"/shops"}>
<Button className="bg-customTeal dark:text-gray-100 dark:hover:opacity-80 dark:bg-Green mt-4">
Continue Shopping
</Button>
</Link>
</div>
)}
</div>
</div>
</div>
</>
);
};

export default Wishlist;
export default WishlistPage;
16 changes: 12 additions & 4 deletions app/(Customer)/shops/[storeId]/components/wishListForm.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
"use client";

import { WishlistPost } from "@/actions/wishlist-actions";
import { Wishlist } from "@prisma/client";
import { Heart } from "lucide-react";
import { useState } from "react";
import toast from "react-hot-toast"; // Import react-hot-toast

interface WishlistForm {
productId: string;
userId?: string;
isWishlisted:Wishlist[]
}

export default function WishlistForm({ productId, userId }: WishlistForm) {
// This is a client-side function for handling form submissions
export default function WishlistForm({ productId, userId ,isWishlisted}: WishlistForm) {

const [wishlisted, setWishlisted] = useState(isWishlisted.length > 0);

const handleSubmit = async (formData: FormData) => {
// Prevent default form submission behavior
if (!userId) {
Expand All @@ -20,6 +25,7 @@ export default function WishlistForm({ productId, userId }: WishlistForm) {
if (response.success) {
// Display success message
toast.success("Added to wishlist!");
setWishlisted(true);
} else {
// Display error message
toast.error(response.error || "error");
Expand Down Expand Up @@ -52,9 +58,11 @@ export default function WishlistForm({ productId, userId }: WishlistForm) {
placeholder="User ID"
required
/>
<button type="submit">
{!wishlisted?<button type="submit">
<Heart />
</button>
</button>:
<Heart fill="red" onClick={()=>{toast.error("item is already wishlisted")}}/>
}
</form>
);
}
Loading

0 comments on commit d8ca637

Please sign in to comment.