Skip to content

Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.

feat(admin): replace Load More buttons with infinite scroll

Khuram Niaz0762ea49f82f
diff --git a/__tests__/CompaniesContainer.spec.tsx b/__tests__/CompaniesContainer.spec.tsx
index e77cff6..cc14f23 100644
--- a/__tests__/CompaniesContainer.spec.tsx
+++ b/__tests__/CompaniesContainer.spec.tsx
@@ -11,6 +11,16 @@ vi.mock("@/actions/company.actions", () => ({
updateCompany: vi.fn(),
}));
+let intersectionCallback: IntersectionObserverCallback | undefined;
+global.IntersectionObserver = class IntersectionObserver {
+ constructor(callback: IntersectionObserverCallback) {
+ intersectionCallback = callback;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+} as any;
+
describe("CompaniesContainer Search Functionality", () => {
const mockCompanies = [
{ id: "1", label: "Amazon", value: "amazon", createdBy: "user-1" },
@@ -22,6 +32,7 @@ describe("CompaniesContainer Search Functionality", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.useFakeTimers({ shouldAdvanceTime: true });
+ intersectionCallback = undefined;
});
afterEach(() => {
@@ -239,11 +250,11 @@ describe("CompaniesContainer Search Functionality", () => {
expect(getCompanyList).toHaveBeenCalledWith(1, 25, "applied", "Amazon");
});
- const loadMoreButton = await screen.findByRole("button", {
- name: /load more/i,
- });
await act(async () => {
- await user.click(loadMoreButton);
+ intersectionCallback!(
+ [{ isIntersecting: true }] as IntersectionObserverEntry[],
+ {} as IntersectionObserver,
+ );
});
await waitFor(() => {
@@ -251,4 +262,56 @@ describe("CompaniesContainer Search Functionality", () => {
});
});
});
+
+ describe("Infinite Scroll", () => {
+ it("should load and append more companies when sentinel becomes visible", async () => {
+ (getCompanyList as any)
+ .mockResolvedValueOnce({ data: mockCompanies, total: 4 })
+ .mockResolvedValueOnce({
+ data: [{ id: "3", label: "Meta", value: "meta", createdBy: "user-1" }],
+ total: 4,
+ });
+
+ render(<CompaniesContainer />);
+
+ await waitFor(() => {
+ expect(screen.getByText("Amazon")).toBeInTheDocument();
+ });
+
+ await act(async () => {
+ intersectionCallback!(
+ [{ isIntersecting: true }] as IntersectionObserverEntry[],
+ {} as IntersectionObserver,
+ );
+ });
+
+ await waitFor(() => {
+ expect(getCompanyList).toHaveBeenCalledWith(2, 25, "applied", undefined);
+ expect(screen.getByText("Meta")).toBeInTheDocument();
+ expect(screen.getByText("Amazon")).toBeInTheDocument();
+ });
+ });
+
+ it("should not fetch more companies once all are loaded", async () => {
+ (getCompanyList as any).mockResolvedValue({
+ data: mockCompanies,
+ total: 2,
+ });
+
+ render(<CompaniesContainer />);
+
+ await waitFor(() => {
+ expect(screen.getByText("Amazon")).toBeInTheDocument();
+ });
+
+ await act(async () => {
+ intersectionCallback?.(
+ [{ isIntersecting: true }] as IntersectionObserverEntry[],
+ {} as IntersectionObserver,
+ );
+ });
+
+ expect(getCompanyList).toHaveBeenCalledTimes(1);
+ });
+ });
});
diff --git a/__tests__/JobLocationsContainer.spec.tsx b/__tests__/JobLocationsContainer.spec.tsx
new file mode 100644
index 0000000..c046b46
--- /dev/null
+++ b/__tests__/JobLocationsContainer.spec.tsx
@@ -0,0 +1,100 @@
+import JobLocationsContainer from "@/components/admin/JobLocationsContainer";
+import { screen, render, waitFor, act } from "@testing-library/react";
+import { getJobLocationsList } from "@/actions/jobLocation.actions";
+
+vi.mock("@/actions/jobLocation.actions", () => ({
+ getJobLocationsList: vi.fn(),
+ deleteJobLocationById: vi.fn(),
+}));
+
+let intersectionCallback: IntersectionObserverCallback | undefined;
+global.IntersectionObserver = class IntersectionObserver {
+ constructor(callback: IntersectionObserverCallback) {
+ intersectionCallback = callback;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+} as any;
+
+describe("JobLocationsContainer", () => {
+ const mockLocations = [
+ { id: "1", label: "Remote", value: "remote", createdBy: "user-1" },
+ { id: "2", label: "New York", value: "new-york", createdBy: "user-1" },
+ ];
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ intersectionCallback = undefined;
+ });
+
+ it("should load and display job locations on mount", async () => {
+ (getJobLocationsList as any).mockResolvedValue({
+ data: mockLocations,
+ total: 2,
+ });
+
+ render(<JobLocationsContainer />);
+
+ await waitFor(() => {
+ expect(screen.getByText("Remote")).toBeInTheDocument();
+ expect(screen.getByText("New York")).toBeInTheDocument();
+ });
+
+ expect(getJobLocationsList).toHaveBeenCalledWith(1, 25, "applied");
+ });
+
+ describe("Infinite Scroll", () => {
+ it("should load and append more job locations when sentinel becomes visible", async () => {
+ (getJobLocationsList as any)
+ .mockResolvedValueOnce({ data: mockLocations, total: 4 })
+ .mockResolvedValueOnce({
+ data: [
+ { id: "3", label: "Austin", value: "austin", createdBy: "user-1" },
+ ],
+ total: 4,
+ });
+
+ render(<JobLocationsContainer />);
+
+ await waitFor(() => {
+ expect(screen.getByText("Remote")).toBeInTheDocument();
+ });
+
+ await act(async () => {
+ intersectionCallback!(
+ [{ isIntersecting: true }] as IntersectionObserverEntry[],
+ {} as IntersectionObserver,
+ );
+ });
+
+ await waitFor(() => {
+ expect(getJobLocationsList).toHaveBeenCalledWith(2, 25, "applied");
+ expect(screen.getByText("Austin")).toBeInTheDocument();
+ expect(screen.getByText("Remote")).toBeInTheDocument();
+ });
+ });
+
+ it("should not fetch more job locations once all are loaded", async () => {
+ (getJobLocationsList as any).mockResolvedValue({
+ data: mockLocations,
+ total: 2,
+ });
+
+ render(<JobLocationsContainer />);
+
+ await waitFor(() => {
+ expect(screen.getByText("Remote")).toBeInTheDocument();
+ });
+
+ await act(async () => {
+ intersectionCallback?.(
+ [{ isIntersecting: true }] as IntersectionObserverEntry[],
+ {} as IntersectionObserver,
+ );
+ });
+
+ expect(getJobLocationsList).toHaveBeenCalledTimes(1);
+ });
+ });
+});
diff --git a/__tests__/JobTitlesContainer.spec.tsx b/__tests__/JobTitlesContainer.spec.tsx
index 97ad164..dc22351 100644
--- a/__tests__/JobTitlesContainer.spec.tsx
+++ b/__tests__/JobTitlesContainer.spec.tsx
@@ -8,6 +8,16 @@ vi.mock("@/actions/jobtitle.actions", () => ({
deleteJobTitleById: vi.fn(),
}));
+let intersectionCallback: IntersectionObserverCallback | undefined;
+global.IntersectionObserver = class IntersectionObserver {
+ constructor(callback: IntersectionObserverCallback) {
+ intersectionCallback = callback;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+} as any;
+
describe("JobTitlesContainer Search Functionality", () => {
const mockTitles = [
{ id: "1", label: "Software Engineer", value: "software engineer", createdBy: "user-1" },
@@ -19,6 +29,7 @@ describe("JobTitlesContainer Search Functionality", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.useFakeTimers({ shouldAdvanceTime: true });
+ intersectionCallback = undefined;
});
afterEach(() => {
@@ -178,11 +189,11 @@ describe("JobTitlesContainer Search Functionality", () => {
);
});
- const loadMoreButton = await screen.findByRole("button", {
- name: /load more/i,
- });
await act(async () => {
- await user.click(loadMoreButton);
+ intersectionCallback!(
+ [{ isIntersecting: true }] as IntersectionObserverEntry[],
+ {} as IntersectionObserver,
+ );
});
await waitFor(() => {
@@ -195,4 +206,63 @@ describe("JobTitlesContainer Search Functionality", () => {
});
});
});
+
+ describe("Infinite Scroll", () => {
+ it("should load and append more job titles when sentinel becomes visible", async () => {
+ (getJobTitleList as any)
+ .mockResolvedValueOnce({ data: mockTitles, total: 4 })
+ .mockResolvedValueOnce({
+ data: [
+ {
+ id: "3",
+ label: "Designer",
+ value: "designer",
+ createdBy: "user-1",
+ },
+ ],
+ total: 4,
+ });
+
+ render(<JobTitlesContainer />);
+
+ await waitFor(() => {
+ expect(screen.getByText("Software Engineer")).toBeInTheDocument();
+ });
+
+ await act(async () => {
+ intersectionCallback!(
+ [{ isIntersecting: true }] as IntersectionObserverEntry[],
+ {} as IntersectionObserver,
+ );
+ });
+
+ await waitFor(() => {
+ expect(getJobTitleList).toHaveBeenCalledWith(2, 25, "applied", undefined);
+ expect(screen.getByText("Designer")).toBeInTheDocument();
+ expect(screen.getByText("Software Engineer")).toBeInTheDocument();
+ });
+ });
+
+ it("should not fetch more job titles once all are loaded", async () => {
+ (getJobTitleList as any).mockResolvedValue({
+ data: mockTitles,
+ total: 2,
+ });
+
+ render(<JobTitlesContainer />);
+
+ await waitFor(() => {
+ expect(screen.getByText("Software Engineer")).toBeInTheDocument();
+ });
+
+ await act(async () => {
+ intersectionCallback?.(
+ [{ isIntersecting: true }] as IntersectionObserverEntry[],
+ {} as IntersectionObserver,
+ );
+ });
+
+ expect(getJobTitleList).toHaveBeenCalledTimes(1);
+ });
+ });
});
diff --git a/__tests__/TagsContainer.spec.tsx b/__tests__/TagsContainer.spec.tsx
index 26bc7a5..66a3ce7 100644
--- a/__tests__/TagsContainer.spec.tsx
+++ b/__tests__/TagsContainer.spec.tsx
@@ -9,6 +9,16 @@ vi.mock("@/actions/tag.actions", () => ({
createTag: vi.fn(),
}));
+let intersectionCallback: IntersectionObserverCallback | undefined;
+global.IntersectionObserver = class IntersectionObserver {
+ constructor(callback: IntersectionObserverCallback) {
+ intersectionCallback = callback;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+} as any;
+
describe("TagsContainer Search Functionality", () => {
const mockTags = [
{
@@ -32,6 +42,7 @@ describe("TagsContainer Search Functionality", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.useFakeTimers({ shouldAdvanceTime: true });
+ intersectionCallback = undefined;
});
afterEach(() => {
@@ -164,11 +175,11 @@ describe("TagsContainer Search Functionality", () => {
expect(getTagList).toHaveBeenCalledWith(1, 25, "React");
});
- const loadMoreButton = await screen.findByRole("button", {
- name: /load more/i,
- });
await act(async () => {
- await user.click(loadMoreButton);
+ intersectionCallback!(
+ [{ isIntersecting: true }] as IntersectionObserverEntry[],
+ {} as IntersectionObserver,
+ );
});
await waitFor(() => {
@@ -176,4 +187,61 @@ describe("TagsContainer Search Functionality", () => {
});
});
});
+
+ describe("Infinite Scroll", () => {
+ it("should load and append more skills when sentinel becomes visible", async () => {
+ (getTagList as any)
+ .mockResolvedValueOnce({ data: mockTags, total: 4 })
+ .mockResolvedValueOnce({
+ data: [
+ {
+ id: "3",
+ label: "TypeScript",
+ value: "typescript",
+ createdBy: "user-1",
+ _count: { jobs: 0, questions: 0, skills: 0 },
+ },
+ ],
+ total: 4,
+ });
+
+ render(<TagsContainer />);
+
+ await waitFor(() => {
+ expect(screen.getByText("React")).toBeInTheDocument();
+ });
+
+ await act(async () => {
+ intersectionCallback!(
+ [{ isIntersecting: true }] as IntersectionObserverEntry[],
+ {} as IntersectionObserver,
+ );
+ });
+
+ await waitFor(() => {
+ expect(getTagList).toHaveBeenCalledWith(2, 25, undefined);
+ expect(screen.getByText("TypeScript")).toBeInTheDocument();
+ expect(screen.getByText("React")).toBeInTheDocument();
+ });
+ });
+
+ it("should not fetch more skills once all are loaded", async () => {
+ (getTagList as any).mockResolvedValue({ data: mockTags, total: 2 });
+
+ render(<TagsContainer />);
+
+ await waitFor(() => {
+ expect(screen.getByText("React")).toBeInTheDocument();
+ });
+
+ await act(async () => {
+ intersectionCallback?.(
+ [{ isIntersecting: true }] as IntersectionObserverEntry[],
+ {} as IntersectionObserver,
+ );
+ });
+
+ expect(getTagList).toHaveBeenCalledTimes(1);
+ });
+ });
});
diff --git a/src/components/admin/CompaniesContainer.tsx b/src/components/admin/CompaniesContainer.tsx
index b97331d..0772c76 100644
--- a/src/components/admin/CompaniesContainer.tsx
+++ b/src/components/admin/CompaniesContainer.tsx
@@ -8,9 +8,10 @@ import { Company } from "@/models/job.model";
import { getCompanyById, getCompanyList } from "@/actions/company.actions";
import { APP_CONSTANTS } from "@/lib/constants";
import Loading from "../Loading";
-import { Button } from "../ui/button";
+import { Loader } from "lucide-react";
import { RecordsCount } from "../RecordsCount";
import { SearchInput } from "../SearchInput";
+import { useInfiniteScroll } from "@/hooks/useInfiniteScroll";
function CompaniesContainer() {
const [companies, setCompanies] = useState<Company[]>([]);
@@ -18,24 +19,30 @@ function CompaniesContainer() {
const [page, setPage] = useState<number>(1);
const [dialogOpen, setDialogOpen] = useState(false);
const [editCompany, setEditCompany] = useState(null);
- const [loading, setLoading] = useState<boolean>(false);
+ const [initialLoading, setInitialLoading] = useState<boolean>(false);
+ const [loadingMore, setLoadingMore] = useState<boolean>(false);
const [searchTerm, setSearchTerm] = useState("");
const hasSearched = useRef(false);
+ const requestIdRef = useRef(0);
const loadCompanies = useCallback(
async (page: number, search?: string) => {
- setLoading(true);
+ const requestId = ++requestIdRef.current;
+ if (page === 1) setInitialLoading(true);
+ else setLoadingMore(true);
const { data, total } = await getCompanyList(
page,
APP_CONSTANTS.RECORDS_PER_PAGE,
"applied",
search
);
+ if (requestId !== requestIdRef.current) return;
if (data) {
setCompanies((prev) => (page === 1 ? data : [...prev, ...data]));
setTotalCompanies(total);
setPage(page);
- setLoading(false);
}
+ setInitialLoading(false);
+ setLoadingMore(false);
},
[]
);
@@ -65,6 +72,16 @@ function CompaniesContainer() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [searchTerm]);
+ const hasMoreCompanies = companies.length < totalCompanies;
+ const sentinelRef = useInfiniteScroll(
+ hasMoreCompanies,
+ initialLoading || loadingMore,
+ useCallback(
+ () => loadCompanies(page + 1, searchTerm || undefined),
+ [loadCompanies, page, searchTerm]
+ )
+ );
+
const onEditCompany = async (companyId: string) => {
const company = await getCompanyById(companyId);
setEditCompany(company);
@@ -78,7 +95,7 @@ function CompaniesContainer() {
<ResponsiveCardHeader>
<div className="flex items-baseline gap-2">
<CardTitle>Companies</CardTitle>
- {!loading && totalCompanies > 0 && (
+ {!initialLoading && totalCompanies > 0 && (
<RecordsCount count={companies.length} total={totalCompanies} label="companies" />
)}
</div>
@@ -98,7 +115,7 @@ function CompaniesContainer() {
</div>
</ResponsiveCardHeader>
<CardContent>
- {loading && <Loading />}
+ {initialLoading && <Loading />}
{companies.length > 0 && (
<>
<CompaniesTable
@@ -108,17 +125,11 @@ function CompaniesContainer() {
/>
</>
)}
- {companies.length < totalCompanies && (
- <div className="flex justify-center p-4">
- <Button
- size="sm"
- variant="outline"
- onClick={() => loadCompanies(page + 1, searchTerm || undefined)}
- disabled={loading}
- className="btn btn-primary"
- >
- {loading ? "Loading..." : "Load More"}
- </Button>
+ {hasMoreCompanies && (
+ <div ref={sentinelRef} className="flex justify-center p-4">
+ {loadingMore && (
+ <Loader className="h-5 w-5 animate-spin text-blue-500" />
+ )}
</div>
)}
</CardContent>
diff --git a/src/components/admin/JobLocationsContainer.tsx b/src/components/admin/JobLocationsContainer.tsx
index 9f6fbf8..8ebbf00 100644
--- a/src/components/admin/JobLocationsContainer.tsx
+++ b/src/components/admin/JobLocationsContainer.tsx
@@ -1,5 +1,5 @@
"use client";
-import { useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { Card, CardContent, CardTitle } from "../ui/card";
import { ResponsiveCardHeader } from "../ResponsiveCardHeader";
import { APP_CONSTANTS } from "@/lib/constants";
@@ -7,28 +7,35 @@ import { JobTitle } from "@prisma/client";
import JobLocationsTable from "./JobLocationsTable";
import { getJobLocationsList } from "@/actions/jobLocation.actions";
import Loading from "../Loading";
-import { Button } from "../ui/button";
+import { Loader } from "lucide-react";
import { RecordsCount } from "../RecordsCount";
+import { useInfiniteScroll } from "@/hooks/useInfiniteScroll";
function JobLocationsContainer() {
const [locations, setLocations] = useState<JobTitle[]>([]);
const [totalJobLocations, setTotalJobLocations] = useState<number>(0);
const [page, setPage] = useState<number>(1);
- const [loading, setLoading] = useState<boolean>(false);
+ const [initialLoading, setInitialLoading] = useState<boolean>(false);
+ const [loadingMore, setLoadingMore] = useState<boolean>(false);
+ const requestIdRef = useRef(0);
const loadJobLocations = useCallback(
async (page: number) => {
- setLoading(true);
+ const requestId = ++requestIdRef.current;
+ if (page === 1) setInitialLoading(true);
+ else setLoadingMore(true);
const { data, total } = await getJobLocationsList(
page,
APP_CONSTANTS.RECORDS_PER_PAGE,
"applied"
);
+ if (requestId !== requestIdRef.current) return;
if (data) {
setLocations((prev) => (page === 1 ? data : [...prev, ...data]));
setTotalJobLocations(total);
setPage(page);
- setLoading(false);
}
+ setInitialLoading(false);
+ setLoadingMore(false);
},
[]
);
@@ -41,6 +48,13 @@ function JobLocationsContainer() {
(async () => await loadJobLocations(1))();
}, [loadJobLocations]);
+ const hasMoreJobLocations = locations.length < totalJobLocations;
+ const sentinelRef = useInfiniteScroll(
+ hasMoreJobLocations,
+ initialLoading || loadingMore,
+ useCallback(() => loadJobLocations(page + 1), [loadJobLocations, page])
+ );
+
return (
<>
<div className="col-span-3">
@@ -48,7 +62,7 @@ function JobLocationsContainer() {
<ResponsiveCardHeader>
<div className="flex items-baseline gap-2">
<CardTitle>Job Locations</CardTitle>
- {!loading && totalJobLocations > 0 && (
+ {!initialLoading && totalJobLocations > 0 && (
<RecordsCount count={locations.length} total={totalJobLocations} label="job locations" />
)}
</div>
@@ -57,7 +71,7 @@ function JobLocationsContainer() {
</div>
</ResponsiveCardHeader>
<CardContent>
- {loading && <Loading />}
+ {initialLoading && <Loading />}
{locations.length > 0 && (
<>
<JobLocationsTable
@@ -66,17 +80,11 @@ function JobLocationsContainer() {
/>
</>
)}
- {locations.length < totalJobLocations && (
- <div className="flex justify-center p-4">
- <Button
- size="sm"
- variant="outline"
- onClick={() => loadJobLocations(page + 1)}
- disabled={loading}
- className="btn btn-primary"
- >
- {loading ? "Loading..." : "Load More"}
- </Button>
+ {hasMoreJobLocations && (
+ <div ref={sentinelRef} className="flex justify-center p-4">
+ {loadingMore && (
+ <Loader className="h-5 w-5 animate-spin text-blue-500" />
+ )}
</div>
)}
</CardContent>
diff --git a/src/components/admin/JobTitlesContainer.tsx b/src/components/admin/JobTitlesContainer.tsx
index 863d833..dbb8551 100644
--- a/src/components/admin/JobTitlesContainer.tsx
+++ b/src/components/admin/JobTitlesContainer.tsx
@@ -7,32 +7,39 @@ import { JobTitle } from "@prisma/client";
import JobTitlesTable from "./JobTitlesTable";
import { getJobTitleList } from "@/actions/jobtitle.actions";
import Loading from "../Loading";
-import { Button } from "../ui/button";
+import { Loader } from "lucide-react";
import { RecordsCount } from "../RecordsCount";
import { SearchInput } from "../SearchInput";
+import { useInfiniteScroll } from "@/hooks/useInfiniteScroll";
function JobTitlesContainer() {
const [titles, setTitles] = useState<JobTitle[]>([]);
const [totalJobTitles, setTotalJobTitles] = useState<number>(0);
const [page, setPage] = useState<number>(1);
- const [loading, setLoading] = useState<boolean>(false);
+ const [initialLoading, setInitialLoading] = useState<boolean>(false);
+ const [loadingMore, setLoadingMore] = useState<boolean>(false);
const [searchTerm, setSearchTerm] = useState("");
const hasSearched = useRef(false);
+ const requestIdRef = useRef(0);
const loadJobTitles = useCallback(
async (page: number, search?: string) => {
- setLoading(true);
+ const requestId = ++requestIdRef.current;
+ if (page === 1) setInitialLoading(true);
+ else setLoadingMore(true);
const { data, total } = await getJobTitleList(
page,
APP_CONSTANTS.RECORDS_PER_PAGE,
"applied",
search
);
+ if (requestId !== requestIdRef.current) return;
if (data) {
setTitles((prev) => (page === 1 ? data : [...prev, ...data]));
setTotalJobTitles(total);
setPage(page);
- setLoading(false);
}
+ setInitialLoading(false);
+ setLoadingMore(false);
},
[]
);
@@ -58,6 +65,16 @@ function JobTitlesContainer() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [searchTerm]);
+ const hasMoreJobTitles = titles.length < totalJobTitles;
+ const sentinelRef = useInfiniteScroll(
+ hasMoreJobTitles,
+ initialLoading || loadingMore,
+ useCallback(
+ () => loadJobTitles(page + 1, searchTerm || undefined),
+ [loadJobTitles, page, searchTerm]
+ )
+ );
+
return (
<>
<div className="col-span-3">
@@ -65,7 +82,7 @@ function JobTitlesContainer() {
<ResponsiveCardHeader>
<div className="flex items-baseline gap-2">
<CardTitle>Job Titles</CardTitle>
- {!loading && totalJobTitles > 0 && (
+ {!initialLoading && totalJobTitles > 0 && (
<RecordsCount count={titles.length} total={totalJobTitles} label="job titles" />
)}
</div>
@@ -79,7 +96,7 @@ function JobTitlesContainer() {
</div>
</ResponsiveCardHeader>
<CardContent>
- {loading && <Loading />}
+ {initialLoading && <Loading />}
{titles.length > 0 && (
<>
<JobTitlesTable
@@ -88,17 +105,11 @@ function JobTitlesContainer() {
/>
</>
)}
- {titles.length < totalJobTitles && (
- <div className="flex justify-center p-4">
- <Button
- size="sm"
- variant="outline"
- onClick={() => loadJobTitles(page + 1, searchTerm || undefined)}
- disabled={loading}
- className="btn btn-primary"
- >
- {loading ? "Loading..." : "Load More"}
- </Button>
+ {hasMoreJobTitles && (
+ <div ref={sentinelRef} className="flex justify-center p-4">
+ {loadingMore && (
+ <Loader className="h-5 w-5 animate-spin text-blue-500" />
+ )}
</div>
)}
</CardContent>
diff --git a/src/components/admin/TagsContainer.tsx b/src/components/admin/TagsContainer.tsx
index 7276f43..223dfb4 100644
--- a/src/components/admin/TagsContainer.tsx
+++ b/src/components/admin/TagsContainer.tsx
@@ -6,35 +6,44 @@ import { Tag } from "@/models/job.model";
import { getTagList } from "@/actions/tag.actions";
import { APP_CONSTANTS } from "@/lib/constants";
import Loading from "../Loading";
-import { Button } from "../ui/button";
+import { Loader } from "lucide-react";
import { RecordsCount } from "../RecordsCount";
import TagsTable from "./TagsTable";
import AddTag from "./AddTag";
import { SearchInput } from "../SearchInput";
+import { useInfiniteScroll } from "@/hooks/useInfiniteScroll";
function TagsContainer() {
const [tags, setTags] = useState<Tag[]>([]);
const [totalTags, setTotalTags] = useState<number>(0);
const [page, setPage] = useState<number>(1);
- const [loading, setLoading] = useState<boolean>(false);
+ const [initialLoading, setInitialLoading] = useState<boolean>(false);
+ const [loadingMore, setLoadingMore] = useState<boolean>(false);
const [searchTerm, setSearchTerm] = useState("");
const hasSearched = useRef(false);
+ const requestIdRef = useRef(0);
const loadTags = useCallback(
async (page: number, search?: string) => {
- setLoading(true);
+ const requestId = ++requestIdRef.current;
+ if (page === 1) setInitialLoading(true);
+ else setLoadingMore(true);
try {
const { data, total } = await getTagList(
page,
APP_CONSTANTS.RECORDS_PER_PAGE,
search,
);
+ if (requestId !== requestIdRef.current) return;
if (data) {
setTags((prev) => (page === 1 ? data : [...prev, ...data]));
setTotalTags(total);
setPage(page);
}
} finally {
- setLoading(false);
+ if (requestId === requestIdRef.current) {
+ setInitialLoading(false);
+ setLoadingMore(false);
+ }
}
},
[],
@@ -61,6 +70,16 @@ function TagsContainer() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [searchTerm]);
+ const hasMoreTags = tags.length < totalTags;
+ const sentinelRef = useInfiniteScroll(
+ hasMoreTags,
+ initialLoading || loadingMore,
+ useCallback(
+ () => loadTags(page + 1, searchTerm || undefined),
+ [loadTags, page, searchTerm],
+ ),
+ );
+
return (
<>
<div className="col-span-3">
@@ -68,7 +87,7 @@ function TagsContainer() {
<ResponsiveCardHeader>
<div className="flex items-baseline gap-2">
<CardTitle>Skills/Tags</CardTitle>
- {!loading && totalTags > 0 && (
+ {!initialLoading && totalTags > 0 && (
<RecordsCount count={tags.length} total={totalTags} label="skills" />
)}
</div>
@@ -82,23 +101,17 @@ function TagsContainer() {
</div>
</ResponsiveCardHeader>
<CardContent>
- {loading && <Loading />}
+ {initialLoading && <Loading />}
{tags.length > 0 && (
<>
<TagsTable tags={tags} reloadTags={reloadTags} />
</>
)}
- {tags.length < totalTags && (
- <div className="flex justify-center p-4">
- <Button
- size="sm"
- variant="outline"
- onClick={() => loadTags(page + 1, searchTerm || undefined)}
- disabled={loading}
- className="btn btn-primary"
- >
- {loading ? "Loading..." : "Load More"}
- </Button>
+ {hasMoreTags && (
+ <div ref={sentinelRef} className="flex justify-center p-4">
+ {loadingMore && (
+ <Loader className="h-5 w-5 animate-spin text-blue-500" />
+ )}
</div>
)}
</CardContent>
diff --git a/src/hooks/useInfiniteScroll.ts b/src/hooks/useInfiniteScroll.ts
new file mode 100644
index 0000000..8d2e20b
--- /dev/null
+++ b/src/hooks/useInfiniteScroll.ts
@@ -0,0 +1,32 @@
+import { useCallback, useEffect, useRef } from "react";
+import { APP_CONSTANTS } from "@/lib/constants";
+
+export function useInfiniteScroll(
+ hasMore: boolean,
+ isLoading: boolean,
+ onLoadMore: () => void
+) {
+ const observerRef = useRef<IntersectionObserver | null>(null);
+ const stateRef = useRef({ hasMore, isLoading, onLoadMore });
+
+ useEffect(() => {
+ stateRef.current = { hasMore, isLoading, onLoadMore };
+ }, [hasMore, isLoading, onLoadMore]);
+
+ return useCallback((node: HTMLDivElement | null) => {
+ observerRef.current?.disconnect();
+ observerRef.current = null;
+ if (!node) return;
+
+ observerRef.current = new IntersectionObserver(
+ ([entry]) => {
+ const { hasMore, isLoading, onLoadMore } = stateRef.current;
+ if (entry.isIntersecting && hasMore && !isLoading) {
+ onLoadMore();
+ }
+ },
+ { threshold: APP_CONSTANTS.INTERSECTION_OBSERVER_THRESHOLD }
+ );
+ observerRef.current.observe(node);
+ }, []);
+}