diff --git a/app/actions/bookmarkProperty.js b/app/actions/bookmarkProperty.js new file mode 100644 index 0000000..a0047d7 --- /dev/null +++ b/app/actions/bookmarkProperty.js @@ -0,0 +1,48 @@ +'use server'; + +import connectDB from '@/config/database'; +import User from '@/models/User'; +import { getSessionUser } from '@/utils/getSessionUser'; +import { revalidatePath } from 'next/cache'; + +async function bookmarkProperty(propertyId) { + await connectDB(); + + const sessionUser = await getSessionUser(); + + if (!sessionUser || !sessionUser.userId) { + return { error: 'User ID is required' }; + } + + const { userId } = sessionUser; + + // Find user in database + const user = await User.findById(userId); + + // Check if property is bookmarked + let isBookmarked = user.bookmarks.includes(propertyId); + console.log(isBookmarked); + + let message; + + if (isBookmarked) { + // If already bookmarked, remove it + user.bookmarks.pull(propertyId); + message = 'Bookmark removed successfully'; + isBookmarked = false; + } else { + // If not bookmarked, add it + user.bookmarks.push(propertyId); + message = 'Bookmark added successfully'; + isBookmarked = true; + } + + console.log(message); + + await user.save(); + revalidatePath('/properties/saved', 'page'); + + return { message, isBookmarked }; +} + +export default bookmarkProperty; diff --git a/components/BookmarkButton.jsx b/components/BookmarkButton.jsx index d134c87..aad485e 100644 --- a/components/BookmarkButton.jsx +++ b/components/BookmarkButton.jsx @@ -1,8 +1,55 @@ +'use client'; +import { useState, useEffect } from 'react'; import { FaBookmark } from 'react-icons/fa'; +import { useSession } from 'next-auth/react'; +import bookmarkProperty from '@/app/actions/bookmarkProperty'; +import { toast } from 'react-toastify'; const BookmarkButton = ({ property }) => { + const { data: session } = useSession(); + const userId = session?.user?.id; + + const [isBookmarked, setIsBookmarked] = useState(false); + const [loading, setLoading] = useState(true); + + useEffect(() => { + if (!userId) { + setLoading(false); + return; + } + + //@todo: Run action to check if property is bookmarked + setLoading(false); + }, [property._id, userId]); + + const handleClick = async () => { + if (!userId) { + toast.error('You need to sign in to bookmark a property'); + return; + } + + try { + const res = await bookmarkProperty(property._id); + if (res.error) { + toast.error(res.error); + } else { + toast.success(res.message); + } + } catch (error) { + console.error('Error bookmarking property:', error); + toast.error('Failed to bookmark property'); + } finally { + setLoading(false); + } + }; + + if (loading) return
Loading...
; + return ( -