Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/search 2 #75

Merged
merged 6 commits into from
Sep 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
.DS_Store
.env
.env.e2e
.idea
.next
.vercel
blob-report
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
.DS_Store
.env
.env.e2e
.idea
.next
.vercel
blob-report
Expand Down
1 change: 1 addition & 0 deletions .vercelignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
.DS_Store
.env
.env.e2e
.idea
.next
.vercel
blob-report
Expand Down
106 changes: 15 additions & 91 deletions src/app/categories/[id]/ClientPage.tsx
Original file line number Diff line number Diff line change
@@ -1,102 +1,46 @@
"use client";

import { CompanyCard, CompanyCards } from "../../../components";
import { CompanyCard, CompanyCards, LoadMoreButton } from "../../../components";
import type {
ExistingCategory,
ExistingCompany,
MultipleDocsResponse
} from "../../../schema";
import { logError, useAppDispatch } from "../../../store";
import { BeatLoader } from "react-spinners";
import { COMPANY_LIMIT } from "../../../consts";
import type { FC } from "react";
import Head from "next/head";
import { PageLayout } from "../../../layouts";
import React, { useCallback, useEffect, useRef, useState } from "react";
import React, { useCallback, useState } from "react";
import { api } from "../../../api";
import { callAsync } from "../../../utils";
import { lang } from "../../../langs";
import { logger } from "../../../services";

export const ClientPage: FC<Props> = ({
categories,
category,
companies: { docs: initialCompanies, nextCursor: initialNextCursor }
}) => {
const [autoMode, setAutoMode] = useState(false);

const [companies, setCompanies] = useState(initialCompanies);

const dispatch = useAppDispatch();

const loadMoreButtonRef = useRef<HTMLButtonElement>(null);

const [loading, setLoading] = useState(false);

const [nextCursor, setNextCursor] = useState(initialNextCursor);

const fetchMoreData = useCallback(() => {
callAsync(async () => {
setAutoMode(true);
setLoading(true);

try {
const response = await api.getCompaniesByCategory(category._id, {
cursor: nextCursor ?? undefined,
limit: COMPANY_LIMIT,
sortBy: "foundedAt",
sortOrder: "desc"
});

if ("error" in response) {
setAutoMode(false);
dispatch(
logError({ error: response, message: response.errorMessage })
);
} else {
setCompanies([...companies, ...response.docs]);
setNextCursor(response.nextCursor);
}
} catch (err) {
setAutoMode(false);
logger.error(err);
} finally {
setLoading(false);
}
const fetchMoreData = useCallback(async () => {
const response = await api.getCompaniesByCategory(category._id, {
cursor: nextCursor ?? undefined,
limit: COMPANY_LIMIT,
sortBy: "foundedAt",
sortOrder: "desc"
});
}, [category, companies, dispatch, nextCursor]);

useEffect(() => {
setAutoMode(false);
setCompanies(initialCompanies);
setLoading(false);
setNextCursor(initialNextCursor);
}, [initialCompanies, initialNextCursor]);

useEffect(() => {
const target = loadMoreButtonRef.current;

if (autoMode && nextCursor && target && !loading) {
const observer = new IntersectionObserver(
entries => {
if (entries.some(entry => entry.isIntersecting)) fetchMoreData();
},
{
root: null,
rootMargin: "0px",
threshold: 1
}
);

observer.observe(target);

return () => {
observer.unobserve(target);
};
if ("error" in response)
dispatch(logError({ error: response, message: response.errorMessage }));
else {
setCompanies([...companies, ...response.docs]);
setNextCursor(response.nextCursor);
}

return undefined;
}, [autoMode, fetchMoreData, loading, nextCursor]);
}, [category, companies, dispatch, nextCursor]);

return (
<>
Expand Down Expand Up @@ -125,27 +69,7 @@ export const ClientPage: FC<Props> = ({
{/* Company cards END */}

{/* More button or spinner */}
{nextCursor && (
<div className="flex justify-center">
<button
className="dark-button relative"
disabled={loading}
onClick={fetchMoreData}
ref={loadMoreButtonRef}
>
{loading ? (
<>
<div className="opacity-0">{lang.LoadMore}</div>
<div className="absolute inset-0 flex justify-center items-center">
<BeatLoader color="#ffffff" />
</div>
</>
) : (
<div>{lang.LoadMore}</div>
)}
</button>
</div>
)}
{nextCursor && <LoadMoreButton fetchMoreData={fetchMoreData} />}
{/* More button or spinner END */}
</PageLayout>
</>
Expand Down
66 changes: 50 additions & 16 deletions src/app/search/ClientPage.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
"use client";

import { BigSpinner, CompanyCard, CompanyCards } from "../../components/";
import {
BigSpinner,
CompanyCard,
CompanyCards,
LoadMoreButton
} from "../../components/";
import type { ExistingCategory, ExistingCompanies } from "../../schema";
import { logError, useAppDispatch } from "../../store";
import { COMPANY_LIMIT } from "../../consts";
import type { FC } from "react";
import { PageLayout } from "../../layouts/";
import React, { useEffect, useState } from "react";
import React, { useCallback, useEffect, useState } from "react";
import { api } from "../../api";
import { useAsyncCallback } from "../../hooks";
import { useSearchParams } from "next/navigation";

export const ClientPage: FC<Props> = ({ categories }) => {
const [companies, setCompanies] = React.useState<ExistingCompanies>({
const [companies, setCompanies] = useState<ExistingCompanies>({
count: 0,
docs: [],
nextCursor: undefined,
total: 0
});

Expand All @@ -26,37 +32,65 @@ export const ClientPage: FC<Props> = ({ categories }) => {

const q = searchParams.get("q");

const fetchMoreData = useCallback(async () => {
const response = await api.getCompanies({
cursor: companies.nextCursor ?? undefined,
limit: COMPANY_LIMIT,
q,
sortBy: "foundedAt",
sortOrder: "desc"
});

if ("error" in response)
dispatch(logError({ error: response, message: response.errorMessage }));
else
setCompanies({
...companies,
docs: [...companies.docs, ...response.docs],
nextCursor: response.nextCursor
});
}, [companies, dispatch, q]);

const { callback: loadCompanies } = useAsyncCallback(async () => {
const nextCompanies = await api.getCompanies({
limit: COMPANY_LIMIT,
q,
sortBy: "foundedAt",
sortOrder: "asc"
sortOrder: "desc"
});

if ("error" in nextCompanies)
dispatch(
logError({ error: nextCompanies, message: nextCompanies.errorMessage })
);
else setCompanies(nextCompanies);
else setCompanies({ ...nextCompanies });

setInitialized(true);
}, [dispatch, q]);

useEffect(loadCompanies, [loadCompanies]);

return initialized ? (
<PageLayout size="xl">
<CompanyCards>
{companies.docs.map(company => (
<CompanyCard
categories={categories}
company={company}
key={company._id}
/>
))}
</CompanyCards>
</PageLayout>
companies.count > 0 ? (
<PageLayout size="xl">
<CompanyCards>
{companies.docs.map(company => (
<CompanyCard
categories={categories}
company={company}
key={company._id}
/>
))}
</CompanyCards>
{companies.nextCursor && (
<LoadMoreButton fetchMoreData={fetchMoreData} />
)}
</PageLayout>
) : (
<div className="py-40 flex justify-center items-center">
<h1>No companies found</h1>
</div>
)
) : (
<div className="py-40 flex justify-center items-center">
<BigSpinner />
Expand Down
90 changes: 90 additions & 0 deletions src/components/buttons/LoadMoreButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
"use client";

import { BeatLoader } from "react-spinners";
import type { FC } from "react";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { callAsync } from "../../utils";
import { lang } from "../../langs";
import { logger } from "../../services";

export const LoadMoreButton: FC<Props> = ({
fetchMoreData: rawFetchMoreData = defaultFetchMoreData
}) => {
const [loading, setLoading] = useState(false);

const [autoMode, setAutoMode] = useState(false);

const loadMoreButtonRef = useRef<HTMLButtonElement>(null);

const fetchMoreData = useCallback(() => {
callAsync(async () => {
setLoading(true);
setAutoMode(true);

try {
await rawFetchMoreData();
} catch (err) {
logger.error(err);
} finally {
setLoading(false);
}
});
}, [rawFetchMoreData]);

useEffect(() => {
const target = loadMoreButtonRef.current;

if (autoMode && target && !loading) {
const observer = new IntersectionObserver(
entries => {
if (entries.some(entry => entry.isIntersecting)) fetchMoreData();
},
{
root: null,
rootMargin: "0px",
threshold: 1
}
);

observer.observe(target);

return () => {
observer.unobserve(target);
};
}

return undefined;
}, [autoMode, fetchMoreData, loading]);

return (
<div className="flex justify-center">
<button
className="dark-button relative"
disabled={loading}
onClick={fetchMoreData}
ref={loadMoreButtonRef}
>
{loading ? (
<>
<div className="opacity-0">{lang.LoadMore}</div>
<div className="absolute inset-0 flex justify-center items-center">
<BeatLoader color="#ffffff" />
</div>
</>
) : (
<div>{lang.LoadMore}</div>
)}
</button>
</div>
);
};

interface Props {
readonly fetchMoreData?: (() => Promise<void>) | undefined;
}

/**
* Default fetch more data function.
*/
// eslint-disable-next-line no-empty-function -- Ok
async function defaultFetchMoreData(): Promise<void> {}
1 change: 1 addition & 0 deletions src/components/buttons/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ export { AsyncButton } from "./AsyncButton";
export { BackButton } from "./BackButton";
export { BadgeButton } from "./BadgeButton";
export { DarkIconButton } from "./DarkIconButton";
export { LoadMoreButton } from "./LoadMoreButton";
export { PrimaryIconButton } from "./PrimaryIconButton";
Loading
Loading