forked from Transparency/kgroad-frontend2
73 lines
1.6 KiB
TypeScript
73 lines
1.6 KiB
TypeScript
"use client";
|
|
|
|
import "./ReportLike.scss";
|
|
import Image from "next/image";
|
|
import like from "./icons/like.svg";
|
|
import { apiInstance } from "@/shared/config/apiConfig";
|
|
import { signIn, useSession } from "next-auth/react";
|
|
import { useEffect } from "react";
|
|
import { usePathname, useRouter } from "@/shared/config/navigation";
|
|
|
|
interface IReportLikeProps {
|
|
count: number;
|
|
report_id: number;
|
|
}
|
|
|
|
const ReportLike: React.FC<IReportLikeProps> = ({
|
|
count,
|
|
report_id,
|
|
}: IReportLikeProps) => {
|
|
const session = useSession();
|
|
|
|
const router = useRouter();
|
|
const pathname = usePathname();
|
|
|
|
const Authorization = `Bearer ${session?.data?.access_token}`;
|
|
const config = {
|
|
headers: {
|
|
Authorization,
|
|
},
|
|
};
|
|
|
|
const checkLike = async () => {
|
|
if (session.status === "unauthenticated") {
|
|
signIn(undefined, { callbackUrl: pathname });
|
|
}
|
|
|
|
const res = await apiInstance.get<{ detail: string }>(
|
|
`/report/${report_id}/like/check/`,
|
|
config
|
|
);
|
|
|
|
return res.data;
|
|
};
|
|
|
|
const likeReport = async () => {
|
|
const isLiked = await checkLike();
|
|
if (isLiked.detail === "Like does not exist!") {
|
|
await apiInstance.post(
|
|
`/report/${report_id}/like/`,
|
|
{},
|
|
config
|
|
);
|
|
} else {
|
|
await apiInstance.post(
|
|
`/report/${report_id}/unlike/`,
|
|
{},
|
|
config
|
|
);
|
|
}
|
|
|
|
router.refresh();
|
|
};
|
|
|
|
return (
|
|
<button onClick={likeReport} className="report-like">
|
|
<Image src={like} alt="Like Icon" />
|
|
<span>{count}</span>
|
|
</button>
|
|
);
|
|
};
|
|
|
|
export default ReportLike;
|