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

[MID-148] add infinite scroll pagination on specialists page #105

Merged
merged 5 commits into from
Mar 29, 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
20 changes: 11 additions & 9 deletions src/app/_components/CardSpecialist/MethodList.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,16 @@ function Method({ id, title, description }) {
<span className="w-full px-3 py-1 text-c3 font-medium text-primary-600" data-tooltip-id={`method_tooltip_${id}`}>
{title}
</span>
<Tooltip
id={`method_tooltip_${id}`}
style={{ backgroundColor: '#FFF', color: '#080809', boxShadow: '0px 0px 7px 1px rgba(0,0,0,0.2)' }}
place="bottom"
opacity={1}
>
<Paragraph className="max-w-64 md:max-w-80">{description}</Paragraph>
</Tooltip>
{description && (
<Tooltip
id={`method_tooltip_${id}`}
style={{ backgroundColor: '#FFF', color: '#080809', boxShadow: '0px 0px 7px 1px rgba(0,0,0,0.2)' }}
place="bottom"
opacity={1}
>
<Paragraph className="max-w-64 md:max-w-80">{description}</Paragraph>
</Tooltip>
)}
</div>
);
}
Expand Down Expand Up @@ -71,7 +73,7 @@ export function MethodList({ methods = [], specializations = [] }) {
}
if (expanded) {
return (
<span className="text-c3 cursor-pointer text-gray-900" onClick={() => setExpanded(false)}>
<span className="cursor-pointer text-c3 text-gray-900" onClick={() => setExpanded(false)}>
Приховати
</span>
);
Expand Down
60 changes: 45 additions & 15 deletions src/app/_components/Specialists/SpecialistList.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
'use client';

import React from 'react';
import { useEffect } from 'react';
import PropTypes from 'prop-types';
import { CardOrganization, CardSpecialist } from '@components/CardSpecialist';
import { useListEntries } from '@hooks';
import { CircularProgress } from '@mui/material';
import { useInView } from 'react-intersection-observer';
import { useSearchParams } from 'next/navigation';
import _ from 'lodash';
import { usePaginatedEntries } from '@/app/_hooks';
import { NoInfoToShow } from '../NoInfoToShow';

function getProperEnding(count) {
Expand All @@ -22,10 +23,25 @@ function getProperEnding(count) {
}
return 'результатів';
}
const loadingTextStyles =
'align-center px-auto flex h-10 w-[170px] flex-col justify-center gap-2 self-center rounded-[100px] bg-primary-200 px-[10px] text-center text-p4 font-bold text-gray-700';

export function SpecialistList({ className }) {
const searchParams = useSearchParams();
const { data, isLoading } = useListEntries(searchParams.toString());

const { ref, inView } = useInView();

const { data, error, isLoading, hasNextPage, fetchNextPage, isSuccess } = usePaginatedEntries(searchParams);
const totalCount = data?.pages?.length && data.pages[0].metaData?.totalCount;

useEffect(() => {
// if the last element is in view and there is a next page, fetch the next page
if (inView && hasNextPage) {
fetchNextPage();
}
// eslint-disable-next-line
}, [hasNextPage, inView]);

const cardStyle = 'my-6 max-w-[900px] rounded-3xl border-2 border-gray-200 px-4 py-5 md:my-10 md:p-10 lg:mx-auto';

if (isLoading)
Expand All @@ -35,7 +51,8 @@ export function SpecialistList({ className }) {
</div>
);

if (!isLoading && !data?.data?.length)
const isNoMatches = !isLoading && !data?.pages?.length;
if (isNoMatches)
return (
<div className="mt-4 flex flex-col gap-4 lg:mt-8 lg:gap-8">
<div className="flex flex-col gap-2 text-p4 font-bold uppercase lg:flex-row lg:gap-1">
Expand All @@ -47,21 +64,34 @@ export function SpecialistList({ className }) {
</div>
);

const { data: entries, totalCount } = data;

return (
<section>
<ul className={className}>
<p className="hidden font-bold uppercase text-primary-600 md:block">{`Знайдено: ${totalCount} ${getProperEnding(totalCount)}`}</p>
{entries.map(entry => (
<li id={entry.id} key={entry.id}>
{entry.gender ? (
<CardSpecialist className={cardStyle} specialist={entry} />
) : (
<CardOrganization className={cardStyle} organization={entry} />
{totalCount && (
<p className="hidden font-bold uppercase text-primary-600 md:block">{`Знайдено: ${totalCount} ${getProperEnding(totalCount)}`}</p>
)}
<>
{isSuccess &&
data.pages?.map(page =>
page.data?.map(entry => (
<li id={entry.id} key={entry.id}>
{entry.specialist ? (
<CardSpecialist className={cardStyle} specialist={entry.specialist} />
) : (
<CardOrganization className={cardStyle} organization={entry.organization} />
)}
</li>
)),
)}
</li>
))}

{isLoading ||
(hasNextPage && (
<div className="mx-auto flex flex-col" ref={ref}>
<p className={loadingTextStyles}>Завантажується</p>
</div>
))}
{error && <div className="mt-10">{('An error has occurred: ', error.message)}</div>}
</>
</ul>
</section>
);
Expand Down
3 changes: 1 addition & 2 deletions src/app/_hooks/api/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
export * from './useTherapy';
export * from './useFeedback';
export * from './useEvent';
export * from './useEventList';
export * from './useDistrict';
export * from './useSearch';
export * from './useEventList';
14 changes: 0 additions & 14 deletions src/app/_hooks/api/useEvent.js

This file was deleted.

19 changes: 12 additions & 7 deletions src/app/_hooks/api/useSearch.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import ky from 'ky';
import { useQuery } from '@tanstack/react-query';
import { useInfiniteQuery } from '@tanstack/react-query';

const specialistKey = 'specialist';
const listEntries = searchParams => ky('/api/search', { searchParams }).json();

export function useListEntries(searchParams) {
return useQuery({
queryKey: [specialistKey, searchParams],
queryFn: async () => ky(`/api/search`, { searchParams }).json(),
export const usePaginatedEntries = searchParams =>
useInfiniteQuery({
queryFn: ({ pageParam = '' }) => {
const params = {
...Object.fromEntries(searchParams.entries()),
lastCursor: pageParam,
};
return listEntries(params);
},
getNextPageParam: lastPage => lastPage?.metaData.lastCursor,
});
}
40 changes: 28 additions & 12 deletions src/app/api/search/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,18 @@ import { prisma } from '@/lib/db';
export async function GET(req) {
const {
type,
// TODO: Uncomment pagination params take and skip when pagination is implemented on the frontend
// take,
// skip,
take,
skip,
lastCursor,
format,
district: districts,
} = getSearchParamsFromRequest(
req,
{
format: undefined,
type: undefined,
// take: 10,
// skip: 0,
take: 5,
skip: 0,
district: undefined,
},
params => ({
Expand All @@ -27,6 +27,7 @@ export async function GET(req) {
district: typeof params.district === 'string' ? [params.district] : params.district,
}),
);

const whereFilter = {
AND: {
supportFocuses: type && {
Expand Down Expand Up @@ -88,7 +89,7 @@ export async function GET(req) {
},
});

const searchEntries = await prisma.searchEntry.findMany({
const searchEntriesPlusOneExtra = await prisma.searchEntry.findMany({
include: {
specialist: {
include: {
Expand Down Expand Up @@ -117,14 +118,29 @@ export async function GET(req) {
orderBy: {
sortString: 'asc',
},
// take,
// skip,
// take one more, to see if there next page available
take: take + 1,
skip,
...(lastCursor && {
skip: 1,
cursor: {
id: lastCursor,
},
}),
});

const data = searchEntries.map(entry => (entry.specialist ? entry.specialist : entry.organization));
// take last one
const isNextPageExist = searchEntriesPlusOneExtra.length === take + 1;
// take rest ( page requested )
const results = searchEntriesPlusOneExtra.slice(0, -1);
const lastResult = results.slice(-1)[0];
const newCursor = lastResult?.id;

return NextResponse.json({
totalCount,
data,
data: results,
metaData: {
totalCount,
lastCursor: newCursor,
hasNextPage: isNextPageExist,
},
});
}
27 changes: 10 additions & 17 deletions src/utils/getSearchParamsFromRequest.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,19 @@
export function getSearchParamsFromRequest(request, defaultValues = {}, transform = null) {
export function getSearchParamsFromRequest(request, defaultValues = {}, transform = it => it) {
if (!request?.url) return {};
try {
const url = new URL(request.url);
const searchParams = {};
url.searchParams.forEach((val, key) => {
if (searchParams[key]) {
if (Array.isArray(searchParams[key])) {
searchParams[key].push(val);
} else {
const currValue = searchParams[key];
searchParams[key] = [currValue, val];
}
} else {
searchParams[key] = val;
const searchParams = Object.fromEntries(url.searchParams.entries());

// Handle multiple values for the same key
url.searchParams.forEach((_, key) => {
if (url.searchParams.getAll(key).length > 1) {
searchParams[key] = url.searchParams.getAll(key);
}
});
Object.entries(defaultValues).forEach(entry => {
const [key, val] = entry;
if (searchParams[key] === undefined) searchParams[key] = val;
});
return transform ? transform(searchParams) : searchParams;

return transform({ ...defaultValues, ...searchParams });
} catch (e) {
console.error(e);
return {};
}
}