Skip to content

Commit

Permalink
resolved the reload bookmark issue
Browse files Browse the repository at this point in the history
  • Loading branch information
Kashyap1ankit committed Oct 20, 2024
1 parent 2d28f42 commit 52606a1
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 72 deletions.
90 changes: 40 additions & 50 deletions src/actions/job.action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,11 @@ import {
getAllRecommendedJobs,
getJobType,
} from '@/types/jobs.types';
import { revalidatePath } from 'next/cache';

type additional = {
isVerifiedJob: boolean;
};

const reloadBookmarkPage = (path: string) => {
revalidatePath(path, 'page');
};

export const createJob = withServerActionAsyncCatcher<
JobPostSchemaType,
ServerActionReturnType<additional>
Expand Down Expand Up @@ -420,7 +415,7 @@ export async function toggleBookmarkAction(userId: string, jobId: string) {

return {
status: 201,
message: 'Bookmakr Deleted Successfully',
message: 'Bookmark Deleted Successfully',
data: deletedBookmark,
};
}
Expand All @@ -446,48 +441,6 @@ export async function toggleBookmarkAction(userId: string, jobId: string) {
}
}

export async function CheckForBookmark(jobId: string) {
try {
const auth = await getServerSession(authOptions);
if (!auth || !auth?.user?.id)
throw new ErrorHandler('Not Authrised', 'UNAUTHORIZED');

if (!jobId) throw new Error('Post is missing');

const userId = auth.user.id;

const checkForUser = await prisma.user.findFirst({
where: { id: userId },
});

if (!checkForUser)
throw new ErrorHandler(
'User with this email does not exist',
'BAD_REQUEST'
);

reloadBookmarkPage('/jobs');

const isBookmarked = await prisma.bookmark.findFirst({
where: {
jobId: jobId,
userId: userId,
},
});
if (!isBookmarked) throw new Error('Post is not Bookmarked');

return {
status: 200,
message: 'Post is Bookmarked',
};
} catch (error) {
return {
status: 404,
message: (error as Error).message,
};
}
}

export async function GetBookmarkByUserId() {
try {
const auth = await getServerSession(authOptions);
Expand All @@ -497,8 +450,6 @@ export async function GetBookmarkByUserId() {

const userId = auth.user.id;

reloadBookmarkPage('/profile/bookmarks');

const getUserBookmarks = await prisma.bookmark.findMany({
where: {
userId: userId,
Expand Down Expand Up @@ -548,3 +499,42 @@ export async function GetBookmarkByUserId() {
};
}
}

export async function GetUserBookmarksId() {
try {
const auth = await getServerSession(authOptions);

if (!auth || !auth?.user?.id)
throw new ErrorHandler('Not Authrised', 'UNAUTHORIZED');

const userId = auth.user.id;

const getUserBookmarks = await prisma.user.findFirst({
where: {
id: userId,
},

select: {
bookmark: {
select: {
jobId: true,
},
},
},
});

if (!getUserBookmarks) throw new Error('No Bookmarked Job found');

return {
status: 200,
message: 'Bookmarks fetched ',
data: getUserBookmarks.bookmark,
};
} catch (error) {
return {
status: 404,
message: (error as Error).message,
data: null,
};
}
}
9 changes: 8 additions & 1 deletion src/app/profile/bookmarks/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,14 @@ export default function BookmarkPage() {
) : (
<div className="h-full overflow-y-scroll no-scrollbar flex flex-col gap-8 my-3">
{bookmarkedJobs?.map(({ job }, index) => {
return <JobCard job={job} key={index} className="w-full" />;
return (
<JobCard
job={job}
key={index}
className="w-full"
isBookmarked={true}
/>
);
})}
</div>
)}
Expand Down
26 changes: 8 additions & 18 deletions src/components/Jobcard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,31 @@ import { JobType } from '@/types/jobs.types';
import _ from 'lodash';
import { cn } from '@/lib/utils';
import { JobSkills } from './job-skills';
import { CheckForBookmark, toggleBookmarkAction } from '@/actions/job.action';
import { toggleBookmarkAction } from '@/actions/job.action';
import { useSession } from 'next-auth/react';
import { useEffect, useState } from 'react';
import { useState } from 'react';
import { useToast } from './ui/use-toast';
import { useRouter } from 'next/navigation';
import BookmarkCardSkeleton from './BookmarkCardSkeletion';

export default function JobCard({
job,

isBookmarked,
className,
}: {
job: JobType;

isBookmarked: boolean;
className?: string;
}) {
const router = useRouter();
const session = useSession();

const [bookmarked, setBookmarked] = useState<boolean>(isBookmarked || false);

const user = session.data?.user;

const { toast } = useToast();

const [bookmarked, setBookmarked] = useState(false);

async function handleBookmarkClick(e: React.MouseEvent) {
e.preventDefault();
e.stopPropagation();
Expand All @@ -46,25 +46,15 @@ export default function JobCard({
});
} catch (error) {
setBookmarked(false);
isBookmarked = false;

toast({
variant: 'destructive',
title: (error as Error).message,
});
}
}

useEffect(() => {
const checkForBookmarkedPost = async () => {
const response = await CheckForBookmark(job.id);
if (response.status !== 200) {
return setBookmarked(false);
}
setBookmarked(true);
};

checkForBookmarkedPost();
}, []);

const handleCardClick = () => {
router.push(`/jobs/${job.id}`);
};
Expand Down
21 changes: 18 additions & 3 deletions src/components/all-jobs.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getAllJobs } from '@/actions/job.action';
import { getAllJobs, GetUserBookmarksId } from '@/actions/job.action';
import { DEFAULT_PAGE, JOBS_PER_PAGE } from '@/config/app.config';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { JobQuerySchemaType } from '@/lib/validators/jobs.validator';
Expand All @@ -10,24 +10,39 @@ import { Pagination, PaginationContent, PaginationItem } from './ui/pagination';
import { PaginationPages } from './ui/paginator';
import JobCard from './Jobcard';
import APP_PATHS from '@/config/path.config';

type PaginatorProps = {
searchParams: JobQuerySchemaType;
};

const AllJobs = async ({ searchParams }: PaginatorProps) => {
const jobs = await getAllJobs(searchParams);
const [jobs, getUserBookmarks] = await Promise.all([
await getAllJobs(searchParams),
await GetUserBookmarksId(),
]);

const userbookmarkArr: { jobId: string }[] | null = getUserBookmarks.data;

if (!jobs.status || !jobs.additional) {
return <div>Error {jobs.message}</div>;
}

const totalPages =
Math.ceil((jobs.additional?.totalJobs || 0) / JOBS_PER_PAGE) ||
DEFAULT_PAGE;
const currentPage = parseInt(searchParams.page?.toString()) || DEFAULT_PAGE;

return (
<div className="bg-background py-4 grid gap-3 w-full">
{jobs.additional.jobs.length > 0 ? (
jobs.additional?.jobs.map((job, index) => (
<JobCard job={job} key={index} />
<JobCard
job={job}
key={index}
isBookmarked={
userbookmarkArr?.some((e) => e.jobId === job.id) || false
}
/>
))
) : (
<Card className="mx-auto max-w-md w-full">
Expand Down

0 comments on commit 52606a1

Please sign in to comment.