Is there a way to change the color of the wishlist icon based on whether the item is in the database? If the item is present, its color should be brown, and if it's not present, the color should be black.
Additionally, I want the ability to toggle between colors. So if an item is already in the database (brown), clicking on the icon should change it to black and remove the item. Clicking again should add the item back to the database, changing the color back to brown.
If this explanation is unclear, feel free to ask! (The value returned from the database is stored in the [itemPresent] hook)
import React, { useState, useCallback, useEffect } from 'react';
import { useParams } from "react-router-dom";
import { connect } from 'react-redux';
import { BsDash, BsPlus } from "react-icons/bs";
import axios from '../../axios-orders';
import Spinner from '../../components/UI/Spinner/Spinner'
import { RiHeart3Fill } from 'react-icons/ri';
const Details = (props) => {
const { id } = useParams();
const [toggleHeart, setToggleHeart] = useState(false);
const [itemPresent, setItemPresent] = useState('');
useEffect(() => {
axios.post('/UserPortal/CartItems/get_wishlist.php', {
customer_id: localStorage.getItem('Id')
})
.then((response) => {
console.log(response.data);
response.data.map((item) => {
return setItemPresent(item.product_id)
})
if(itemPresent === id){
console.log('[item]',itemPresent)
}
});
},[toggleHeart,id,itemPresent])
var c = props.orders.find(product => product.id === id);
const changeColor = useCallback(() => {
setToggleHeart(!toggleHeart);
const data = {
customer_id: localStorage.getItem('Id'),
name: c.name,
price: c.price,
description: c.description,
quantity: c.quantity,
product_id : c.id
};
axios.post('/UserPortal/CartItems/wishlist.php', data )
.then((response) => {
console.log(response.data);
});
},[toggleHeart,c.id,c.name,c.price,c.description,c.quantity]);
if(props.orders.length === 0){
return <Spinner/>;
}
return (
<div className="details__info">
{localStorage.getItem('email')
? itemPresent
? <RiHeart3Fill className={
toggleHeart ? 'heart active' : 'heart'
} onClick={changeColor}/>
: <RiHeart3Fill className="heart" onClick={changeColor}/>
: <RiHeart3Fill className="heart"/>
}
</div>
);
CSS FILE
.heart{
font-size: 35px;
color:rgb(182, 173, 173);
margin-top: 7px;
width: 70px;
outline: none;
text-transform: uppercase;
cursor: pointer;
font-weight: bold;
&:hover{
color: rgb(192, 39, 39);
}
&.active {
color: rgb(192, 39, 39);
}
}