Skip to content

Commit

Permalink
ft(invitationPagination): Improve invitation table pagination
Browse files Browse the repository at this point in the history
  • Loading branch information
Oliviier-dev committed Oct 18, 2024
1 parent 7d95521 commit afd591c
Show file tree
Hide file tree
Showing 5 changed files with 214 additions and 37 deletions.
86 changes: 82 additions & 4 deletions src/components/InvitationTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,23 @@ import { toast } from 'react-toastify';
import DataPagination from './DataPagination';
import SkeletonTable from '../Skeletons/SkeletonTable';

export interface InvitationVariables {
limit: number,
offset: number,
role?: string,
status?: string
}
interface TableData {
data: any[];
columns: any;
error: string | null;
loading?: boolean;
className?: string;
totalInvitations?: number;
fetchNextInvitations: ({limit, offset}: InvitationVariables) => void;
}

function DataTableStats({ data, columns, error, loading }: TableData) {
function DataTableStats({ data, columns, error, loading, fetchNextInvitations, totalInvitations }: TableData) {
const [filterInput, setFilterInput] = useState('');
const { t } = useTranslation();
const [pageIndex, setPageIndex] = useState(0);
Expand Down Expand Up @@ -53,6 +61,71 @@ function DataTableStats({ data, columns, error, loading }: TableData) {
state: { pageIndex: currentPageIndex, pageSize },
} = tableInstance;

// const invitationNextPageHandler = () => {
// console.log(pageIndex, pageSize)
// // Check if more data needs to be fetched
// if ((data.length - (pageSize * (pageIndex + 1))) < 0) {
// console.log('in------!!!!')
// fetchNextInvitations({limit: pageSize, offset: data.length})
// return
// }

// // Check if there's less data left to fill a new page
// if ((data.length - (pageSize * (pageIndex + 1))) < pageSize) {
// console.log('in------!!!!2')
// fetchNextInvitations({limit: pageSize, offset: data.length})
// setPageIndex(prevData => prevData + 1)
// nextPage()
// return
// }

// const totalPages = data.length / pageSize
// // Check if the user is on the last page
// if (totalPages <= (pageIndex + 1)) {
// logger.debug('in------!!!!3')
// fetchNextInvitations({limit: pageSize, offset: data.length})
// setPageIndex(prevData => prevData + 1)
// } else {
// nextPage()
// }
// }

// // useEffect(() => {
// // invitationNextPageHandler()
// // }, [pageSize])
// useEffect(() => {
// setPageIndex(currentPageIndex);
// }, [currentPageIndex]);

const invitationNextPageHandler = () => {
console.log(data)

Check failure on line 101 in src/components/InvitationTable.tsx

View workflow job for this annotation

GitHub Actions / build

Unexpected console statement
const totalFetchedData = data.length;
const totalPages = Math.ceil(totalInvitations / pageSize);
const currentPage = pageIndex + 1;

// If current page is the last one, stop fetching
if (currentPage >= totalPages) {
console.log('shii')

Check failure on line 108 in src/components/InvitationTable.tsx

View workflow job for this annotation

GitHub Actions / build

Unexpected console statement
return;
}

// Check if more data needs to be fetched
const currentOffset = pageSize * currentPage;

if (totalFetchedData <= currentOffset) {
fetchNextInvitations({ limit: pageSize, offset: totalFetchedData });
setPageIndex(prevIndex => prevIndex + 1); // Increment page index after fetching
return;
}

// If there's enough data to display the next page, simply move to the next page
if (totalFetchedData > currentOffset) {
console.log('Moving to the next page...');

Check failure on line 123 in src/components/InvitationTable.tsx

View workflow job for this annotation

GitHub Actions / build

Unexpected console statement
nextPage();
setPageIndex(prevIndex => prevIndex + 1);
}
};

useEffect(() => {
setPageIndex(currentPageIndex);
}, [currentPageIndex]);
Expand All @@ -69,6 +142,11 @@ function DataTableStats({ data, columns, error, loading }: TableData) {
setFilterInput(value);
};

const invitationPageOption = [];
for (let i = 0; i < totalInvitations/pageSize; i=i+1) {
invitationPageOption.push(i);
}

return (
<div className="relative">
<div className="flex items-center justify-between pb-6 " />
Expand Down Expand Up @@ -147,15 +225,15 @@ function DataTableStats({ data, columns, error, loading }: TableData) {
</div>
<div className="px-6 py-4">
<DataPagination
pageOptions={pageOptions}
canNextPage={canNextPage}
pageOptions={invitationPageOption}
canNextPage={true}
gotoPage={gotoPage}
columnLength={columns.length}
canPreviousPage={canPreviousPage}
pageSize={pageSize}
setPageSize={setPageSize}
previousPage={previousPage}
nextPage={nextPage}
nextPage={invitationNextPageHandler}
pageCount={pageCount}
pageIndex={pageIndex}
/>
Expand Down
135 changes: 103 additions & 32 deletions src/pages/invitation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { LuHourglass } from 'react-icons/lu';
import { BsPersonFillX } from 'react-icons/bs';
import { toast } from 'react-toastify';
import InvitationCard from '../components/InvitationCard';
import DataTableStats from '../components/InvitationTable';
import InvitationModal from './invitationModalComponet';
import { GET_INVITATIONS_STATISTICS_QUERY } from '../queries/invitationStats.queries';
import InvitationCardSkeleton from '../Skeletons/InvitationCardSkeleton';
Expand All @@ -28,6 +27,8 @@ import {
GET_ROLES_AND_STATUSES,
} from '../queries/invitation.queries';
import { isValid } from 'date-fns';
import DataTableStats, { InvitationVariables } from '../components/InvitationTable';
import stack from '../utils/Stack';

interface Invitee {
email: string;
Expand Down Expand Up @@ -85,6 +86,12 @@ function Invitation() {
role: '',
status: '',
});
const [invitationData, setInvitationData] = useState<{invitations: any[], totalInvitations: number}>({invitations:[], totalInvitations: 0})
const usedQuery = stack.isEmpty() ? 'all' : stack.peek();
const [previousQuery, setPreviousQuery] = useState(usedQuery);
const [previousFilter, setPreviousFilter] = useState({ role: '', status: '' });
const [previousSearchQuery, setPreviousSearchQuery] = useState("");

const[filterDisabled,setFilterDisabled]=useState<boolean>(true)
const modalRef = useRef<any>(null);
const organizationToken = localStorage.getItem('orgToken');
Expand Down Expand Up @@ -133,6 +140,26 @@ function Invitation() {
fetchPolicy: 'network-only',
});

const [
fetchInvitations,
{ data: searchData, loading: searchLoading, error: searchError },
] = useLazyQuery(GET_INVITATIONS, {
variables: {
query: searchQuery,
orgToken: organizationToken,
sortBy:sortBy
},
fetchPolicy: 'network-only',
});
const [
filterInvitations,
{ data: filterData, loading: filterLoad, error: filterError },
] = useLazyQuery(GET_ROLES_AND_STATUSES, {
variables:filterVariables,
fetchPolicy: 'network-only',
});


useEffect(() => {
if (invitationStats) {
setSelectedStatus(''); // Set the fetched status as the default value
Expand All @@ -141,8 +168,8 @@ function Invitation() {

// Set email and role when modal opens
useEffect(() => {
if (data && data.getAllInvitations) {
const invitation = data.getAllInvitations.invitations.find(
if (invitationData.invitations.length) {
const invitation = invitationData.invitations.find(
(inv: Invitationn) => inv.id === selectedInvitationId,
);

Expand All @@ -151,8 +178,7 @@ function Invitation() {
setRole(invitation.invitees[0].role);
}
}
}, [data, selectedInvitationId]);

}, [invitationData, selectedInvitationId]);
useEffect(() => {
const handleClickOutside = (event: any) => {
if (modalRef.current && !modalRef.current.contains(event.target)) {
Expand Down Expand Up @@ -197,31 +223,12 @@ function Invitation() {
setUpdateInviteeModel(newState);
};

const [
fetchInvitations,
{ data: searchData, loading: searchLoading, error: searchError },
] = useLazyQuery(GET_INVITATIONS, {
variables: {
query: searchQuery,
orgToken: organizationToken,
sortBy:sortBy
},
fetchPolicy: 'network-only',
});
const [
filterInvitations,
{ data: filterData, loading: filterLoad, error: filterError },
] = useLazyQuery(GET_ROLES_AND_STATUSES, {
variables:filterVariables,
fetchPolicy: 'network-only',
});

useEffect(() => {
if (filterVariables.role || filterVariables.status) {
filterInvitations({
variables: {
role: filterVariables.role || null,
status:filterVariables.status || null,
role: filterVariables.role || "",
status:filterVariables.status || "",
orgToken: organizationToken,
sortBy:sortBy
},
Expand All @@ -248,15 +255,17 @@ function Invitation() {
Array.isArray(searchData.getInvitations.invitations)
) {
setInvitations(searchData.getInvitations.invitations);
setTotalInvitations(searchData.getInvitations.totalInvitations);
} else if (filterData && filterData.filterInvitations) {
setInvitations(filterData.filterInvitations.invitations);
setTotalInvitations(filterData.filterInvitations.totalInvitations);
} else if (data && data.getAllInvitations) {
setInvitations(data.getAllInvitations.invitations);
setTotalInvitations(data.getAllInvitations.totalInvitations);
} else if (data && invitationData) {
setInvitations(invitationData.invitations);
setTotalInvitations(invitationData.totalInvitations);
}
}, [
data,
invitationData,
searchData,
queryLoading,
searchLoading,
Expand All @@ -267,6 +276,27 @@ function Invitation() {
filterError,
]);

useEffect(() => {

if (usedQuery === 'all' && data && data.getAllInvitations) {
// If the previous query was 'all', append the new invitations
if (previousQuery === 'all') {
setInvitationData(prevData => ({
invitations: [...prevData.invitations, ...data.getAllInvitations.invitations],
totalInvitations: data.getAllInvitations.totalInvitations
}));
} else {
// If the previous query was not 'all', reset and set the new invitations
setInvitationData({
invitations: [...data.getAllInvitations.invitations],
totalInvitations: data.getAllInvitations.totalInvitations
});
}
}
// Update the previous query after processing
setPreviousQuery(usedQuery);
}, [data, usedQuery]);

const handleSearch = () => {
if (!searchQuery.trim()) {
setError('Search query cannot be empty');
Expand All @@ -276,6 +306,7 @@ function Invitation() {
setInvitations([]);
setError(null);
setLoading(false);
stack.push("search");

fetchInvitations({ variables: { query: searchQuery } });
};
Expand Down Expand Up @@ -305,10 +336,12 @@ const handleStatusChange=(e:React.ChangeEvent<HTMLSelectElement>)=>{
return;
}
setInvitations([]);
setInvitationData({invitations: [], totalInvitations: 0});
setError(null);
setLoading(false);
stack.push("filter");

setFilterVariables({
setFilterVariables({
role: selectedRole,
status: typeof selectedStatus === 'string' ? selectedStatus : '',
});
Expand Down Expand Up @@ -344,6 +377,37 @@ const handleStatusChange=(e:React.ChangeEvent<HTMLSelectElement>)=>{
validateEmail(newEmail); // Validate on change
};

// Refetching Invitation
const fetchNextInvitationsHandler = ({limit, offset}: InvitationVariables) => {
const previousUsedQuery = stack.peek()

if(previousUsedQuery === 'filter'){
filterInvitations({
variables: {
role: filterVariables.role || "",
status: filterVariables.status || "",
limit,
offset,
orgToken: organizationToken
},
});
} else {
refetch({limit, offset})
}
}

useEffect(() => {
if (filterData && filterData.filterInvitations) {
setInvitationData((prevData) => ({
invitations: [
...prevData.invitations,
...filterData.filterInvitations.invitations,
],
totalInvitations: filterData.filterInvitations.totalInvitations,
}));
}
}, [filterData]);

// Defining invitation table
let content;
const capitalizeStrings = (str: string): string => {
Expand Down Expand Up @@ -503,8 +567,9 @@ const handleStatusChange=(e:React.ChangeEvent<HTMLSelectElement>)=>{
];

const datum: any = [];
if (invitations && invitations.length > 0) {
invitations.forEach((invitation) => {

if (invitations && invitationData.invitations.length > 0) {
invitationData.invitations.forEach((invitation) => {
invitation.invitees?.forEach((data: any) => {
let entry: any = {};
entry.email = data.email;
Expand All @@ -522,6 +587,8 @@ const handleStatusChange=(e:React.ChangeEvent<HTMLSelectElement>)=>{
columns={columns}
loading={loading}
error={error}
totalInvitations = {totalInvitations}
fetchNextInvitations={fetchNextInvitationsHandler}
/>
);
} else if (error || searchError || filterError) {
Expand All @@ -531,6 +598,8 @@ const handleStatusChange=(e:React.ChangeEvent<HTMLSelectElement>)=>{
columns={columns}
loading={loading}
error={error}
totalInvitations = {totalInvitations}
fetchNextInvitations={fetchNextInvitationsHandler}
/>
);
} else {
Expand All @@ -541,6 +610,8 @@ const handleStatusChange=(e:React.ChangeEvent<HTMLSelectElement>)=>{
columns={columns}
loading={loading}
error={error}
totalInvitations = {totalInvitations}
fetchNextInvitations={fetchNextInvitationsHandler}
/>
</>
);
Expand Down
Loading

0 comments on commit afd591c

Please sign in to comment.