79 lines
2.8 KiB
TypeScript
79 lines
2.8 KiB
TypeScript
import { use, useEffect, useState } from "react";
|
|
import { AuthContext } from "../../context/AuthContext";
|
|
import { useNavigate } from "react-router-dom";
|
|
import { EngagementFavoriteRecipe } from "../../services/EngagementService";
|
|
import { isApiError } from "../../types/api/error";
|
|
|
|
|
|
interface FavoriteButtonProps {
|
|
favorite: boolean | undefined;
|
|
id: number | undefined;
|
|
}
|
|
|
|
export default function FavoriteButton({ favorite, id }: FavoriteButtonProps) {
|
|
// CONTEXT
|
|
const { isLoggedIn } = use(AuthContext);
|
|
const navigate = useNavigate();
|
|
|
|
const [_favorite, setFavorite] = useState<boolean>();
|
|
|
|
const clickHandler = async () => {
|
|
// This button cannot be used if not logged in
|
|
if (!isLoggedIn) {
|
|
await navigate("/v2/web/login");
|
|
return;
|
|
}
|
|
|
|
if (!id) return;
|
|
|
|
// Toggle button first, to feel fast
|
|
setFavorite(!_favorite);
|
|
|
|
const result = await EngagementFavoriteRecipe(id);
|
|
if (isApiError(result)) {
|
|
console.error(result.message);
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
if (favorite)
|
|
setFavorite(favorite);
|
|
|
|
}, [favorite]);
|
|
|
|
return _favorite ? (
|
|
<button
|
|
className="flex items-center justify-center gap-x-1 rounded-lg border border-blue-300 bg-blue-50 text-gray-800 px-6 py-3 flex-grow hover:bg-blue-100 hover:border-blue-500 duration-300 cursor-pointer"
|
|
onClick={() => void clickHandler()}
|
|
>
|
|
<svg className="h-6 text-red-500" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
<path
|
|
d="M2 9.1371C2 14 6.01943 16.5914 8.96173 18.9109C10 19.7294 11 20.5 12 20.5C13 20.5 14 19.7294 15.0383 18.9109C17.9806 16.5914 22 14 22 9.1371C22 4.27416 16.4998 0.825464 12 5.50063C7.50016 0.825464 2 4.27416 2 9.1371Z"
|
|
fill="currentColor"
|
|
></path>
|
|
</svg>
|
|
Unfavorite
|
|
</button>
|
|
|
|
) : (
|
|
<button
|
|
className="flex items-center justify-center gap-x-1 rounded-lg border border-gray-300 text-gray-800 px-6 py-3 flex-grow hover:bg-gray-50 hover:border-blue-300 duration-300 cursor-pointer"
|
|
onClick={() => void clickHandler()}
|
|
>
|
|
<svg className="h-6" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
<path
|
|
fillRule="evenodd"
|
|
clipRule="evenodd"
|
|
d="M12 6.00019C10.2006 3.90317 7.19377 3.2551 4.93923 5.17534C2.68468 7.09558 2.36727 10.3061 4.13778 12.5772C5.60984 14.4654 10.0648 18.4479 11.5249 19.7369C11.6882 19.8811 11.7699 19.9532 11.8652 19.9815C11.9483 20.0062 12.0393 20.0062 12.1225 19.9815C12.2178 19.9532 12.2994 19.8811 12.4628 19.7369C13.9229 18.4479 18.3778 14.4654 19.8499 12.5772C21.6204 10.3061 21.3417 7.07538 19.0484 5.17534C16.7551 3.2753 13.7994 3.90317 12 6.00019Z"
|
|
stroke="currentColor"
|
|
strokeWidth="2"
|
|
strokeLinecap="round"
|
|
strokeLinejoin="round"
|
|
></path>
|
|
</svg>
|
|
Favorite
|
|
</button>
|
|
|
|
);
|
|
}
|