Clicking the heart once should keep it filled the heart with red. click it again remove…
- User
Clicking the heart once should keep it filled the heart with red. click it again remove that fill. 'use client' import React, { useState } from 'react'; import { Heart } from 'lucide-react'; import { useRouter } from 'next/navigation'; import { motion } from 'framer-motion'; import { getWishlistByProductId, addWishlist, deleteWishlist } from '@/lib/features/wishlistSlice'; import { useAppDispatch, useAppSelector } from "@/lib/hook"; import { AlertDialog, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog"; import { Button } from "@/components/ui/button";
const WishlistHeart = ({ productId }) => { const isAuthenticated = useAppSelector((state) => state.auth.isAuthenticated); const wishlistItem = useAppSelector((state) => getWishlistByProductId(state, productId)); const dispatch = useAppDispatch(); const router = useRouter(); const [showDialog, setShowDialog] = useState(false); const [isRedirecting, setIsRedirecting] = useState(false);
const handleClick = async (e) => { e.stopPropagation() if (!isAuthenticated) { setShowDialog(true); return; } try { const method = wishlistItem ? "DELETE" : "POST"; const response = await fetch("https://api.naayiq.com/wishlist", { method: method, headers: { 'Content-Type': 'application/json', }, credentials: "include", body: JSON.stringify({ productId }), }); if (response.ok) { if (wishlistItem) { dispatch(deleteWishlist(wishlistItem.id)); } else { const newWishlistItem = await response.json(); dispatch(addWishlist(newWishlistItem)); } } else { console.error('Failed to update wishlist'); } } catch (error) { console.error('Error updating wishlist:', error); } }; const handleSignIn = (e) => { e.preventDefault(); setIsRedirecting(true); setTimeout(() => { router.push('/signin'); }, 1000); }; const handleCancel = () => { setShowDialog(false); }; return ( <> <div className="relative"> <motion.div whileTap={{ scale: 0.8 }} transition={{ duration: 0.3 }} > <Heart className={`w-[1.85rem] h-[1.85rem] z-10 stroke-[1.2] ${ wishlistItem ? "fill-[#C91C1C] stroke-[#C91C1C]" : "fill-transparent stroke-[#C91C1C] hover:fill-[#C91C1C]" } cursor-pointer transition-colors duration-300`} onClick={handleClick} /> </motion.div> </div> <AlertDialog open={showDialog} onOpenChange={setShowDialog}> <AlertDialogContent className="z-50"> <AlertDialogHeader> <AlertDialogTitle className="font-sans font-medium">Sign in required</AlertDialogTitle> <AlertDialogDescription className="font-serif"> You need to sign in first to add items to your wishlist. </AlertDialogDescription> </AlertDialogHeader> <AlertDialogFooter className="font-serif"> <Button variant="outline" onClick={handleCancel}>Cancel</Button> <Button onClick={handleSignIn} disabled={isRedirecting}> {isRedirecting ? 'Redirecting' : 'Sign In'} </Button> </AlertDialogFooter> </AlertDialogContent> </AlertDialog> </> );};
export default WishlistHeart;
- Assistant
Your
WishlistHeartcomponent is designed to toggle a heart icon's filled state based on whether a product is in the user's wishlist. From your description and the provided code, it appears that clicking the heart should:- Add to Wishlist: If the product isn't in the wishlist, clicking the heart fills it with red and adds the product to the wishlist.
- Remove from Wishlist: If the product is already in the wishlist, clicking the heart removes it and clears the red fill.
Here's a breakdown of your implementation and some suggestions to ensure it functions as expected.
Code Review
1. Component Structure and State Management
You're using Redux (with
useAppSelectoranduseAppDispatch) to manage the wishlist state. The component checks if a product is in the wishlist and updates the UI accordingly.const isAuthenticated = useAppSelector((state) => state.auth.isAuthenticated); const wishlistItem = useAppSelector((state) => getWishlistByProductId(state, productId));2. Handling Click Events
The
handleClickfunction manages adding or removing items from the wishlist based on the current state (wishlistItem).const handleClick = async (e) => { e.stopPropagation(); if (!isAuthenticated) { setShowDialog(true); return; } try { const method = wishlistItem ? "DELETE" : "POST"; const response = await fetch("https://api.naayiq.com/wishlist", { method, headers: { 'Content-Type': 'application/json', }, credentials: "include", body: JSON.stringify({ productId }), }); if (response.ok) { if (wishlistItem) { dispatch(deleteWishlist(wishlistItem.id)); } else { const newWishlistItem = await response.json(); dispatch(addWishlist(newWishlistItem)); } } else { console.error('Failed to update wishlist'); } } catch (error) { console.error('Error updating wishlist:', error); } };3. Rendering the Heart Icon
The heart icon's appearance changes based on whether the item is in the wishlist.
<Heart className={`w-[1.85rem] h-[1.85rem] z-10 stroke-[1.2] ${ wishlistItem ? "fill-[#C91C1C] stroke-[#C91C1C]" : "fill-transparent stroke-[#C91C1C] hover:fill-[#C91C1C]" } cursor-pointer transition-colors duration-300`} onClick={handleClick} />Suggestions and Improvements
-
Ensure Selector Accuracy:
- Selector Function: Verify that your
getWishlistByProductIdselector accurately retrieves the wishlist item based on theproductId. It should return the specific wishlist item ornull/undefinedif not present.
// Example selector implementation export const getWishlistByProductId = (state, productId) => state.wishlist.items.find(item => item.productId === productId); - Selector Function: Verify that your
-
Optimistic UI Updates:
To enhance user experience, consider updating the UI optimistically before the API call completes. This approach makes the UI feel more responsive.
const handleClick = async (e) => { e.stopPropagation(); if (!isAuthenticated) { setShowDialog(true); return; } const method = wishlistItem ? "DELETE" : "POST"; // Optimistically update the UI if (wishlistItem) { dispatch(deleteWishlist(wishlistItem.id)); } else { dispatch(addWishlist({ productId })); // You might need to include other necessary fields } try { const response = await fetch("https://api.naayiq.com/wishlist", { method, headers: { 'Content-Type': 'application/json', }, credentials: "include", body: JSON.stringify({ productId }), }); if (!response.ok) { // Revert the optimistic update if the API call fails if (wishlistItem) { dispatch(addWishlist(wishlistItem)); } else { dispatch(deleteWishlist(productId)); } console.error('Failed to update wishlist'); } } catch (error) { // Revert the optimistic update on error if (wishlistItem) { dispatch(addWishlist(wishlistItem)); } else { dispatch(deleteWishlist(productId)); } console.error('Error updating wishlist:', error); } }; -
Handling API Responses:
Ensure that your backend API correctly handles
POSTandDELETErequests and returns the appropriate responses. For instance, after adding to the wishlist (POST), the API should return the new wishlist item with its unique identifier. -
Accessibility Considerations:
- Keyboard Accessibility: Ensure that the heart icon is focusable and can be toggled using the keyboard.
- ARIA Labels: Add appropriate
aria-labelattributes to communicate the button's purpose to assistive technologies.
<Heart aria-label={wishlistItem ? "Remove from wishlist" : "Add to wishlist"} role="button" tabIndex={0} onKeyPress={(e) => { if (e.key === 'Enter' || e.key === ' ') { handleClick(e); } }} // ...rest of your props /> -
Loading State:
Incorporate a loading state to prevent multiple rapid clicks and provide feedback while the API request is in progress.
const [isLoading, setIsLoading] = useState(false); const handleClick = async (e) => { e.stopPropagation(); if (isLoading) return; // Prevent multiple clicks if (!isAuthenticated) { setShowDialog(true); return; } setIsLoading(true); // ...rest of your logic setIsLoading(false); }; // Update the Heart component to reflect loading state if desired -
Error Feedback:
Inform users if adding or removing from the wishlist fails. You can use toast notifications or inline error messages.
import { toast } from 'react-toastify'; // Example using react-toastify // Inside your catch blocks toast.error('Failed to update wishlist. Please try again.'); -
Refactoring for Clarity:
To improve readability, you can separate API interaction logic from the component.
// api.js export const updateWishlist = async (productId, method) => { const response = await fetch("https://api.naayiq.com/wishlist", { method, headers: { 'Content-Type': 'application/json', }, credentials: "include", body: JSON.stringify({ productId }), }); return response; };// In your component import { updateWishlist } from '@/lib/api'; const handleClick = async (e) => { // ...previous logic try { const response = await updateWishlist(productId, method); // ...rest of your logic } catch (error) { // ...error handling } };
Final Thoughts
Your implementation is on the right track for toggling the wishlist state via the heart icon. By ensuring that selectors are accurate, handling UI states optimistically, and providing user feedback, you can enhance both functionality and user experience. If you encounter specific issues or errors while implementing these suggestions, feel free to provide more details, and I’d be happy to assist further!