/
dbataeva
/
tasksApp
Обзор
Документация
Войти
/
dbataeva
/
tasksApp
Код
Запросы
2
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
finalProject
dogFood/src/features/LikeButton/LikeButton.tsx
65 строк
2 KB
Daria Bataeva
feat(finalProject): add useUser
17 ноя 2025, 19:39
17 ноя 2025, 19:39
5fafdda
Код
Авторство
О чём код?
import { Favorite, FavoriteBorder } from '@mui/icons-material'; import { IErrorResponse, useDeleteLikeProductMutation, useSetLikeProductMutation, } from 'entities/product'; import { userSelectors } from 'entities/user'; import { useUser } from 'entities/user'; import { memo, startTransition, useOptimistic, useState } from 'react'; import { toast } from 'react-toastify'; import { useAppSelector } from 'shared/store/utils'; type TLikeButtonProps = { product: Product; }; export const LikeButton = memo(({ product }: TLikeButtonProps) => { const user = useUser(); const accessToken = useAppSelector(userSelectors.getAccessToken); const [setLike] = useSetLikeProductMutation(); const [deleteLike] = useDeleteLikeProductMutation(); const [isLiked, setIsLiked] = useState( product?.likes.some((l) => l.userId === user?.id) ); const [optimisticLikeState, updateOptimisticLikeState] = useOptimistic< boolean, void >(isLiked, (state) => !state); const toggleLike = async () => { if (!accessToken) { toast.warning('Вы не авторизованы'); return; } let response; updateOptimisticLikeState(); startTransition(async () => { if (isLiked) { response = await deleteLike({ id: `${product.id}` }); } else { response = await setLike({ id: `${product.id}` }); } if (response?.error) { const error = response.error as IErrorResponse; updateOptimisticLikeState(); toast.error(error.data.message); } else { setIsLiked((prev) => !prev); } }); }; return optimisticLikeState ? ( <Favorite onClick={toggleLike} /> ) : ( <FavoriteBorder onClick={toggleLike} /> ); }); LikeButton.displayName = 'LikeButton';