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

Conditionaly renders pagination component if number of entries is more than results per page #9004

Conversation

mnshrm
Copy link
Contributor

@mnshrm mnshrm commented Nov 5, 2024

Added logic which makes sure, if number of entries for staff capacity is less than or equal to results per page of that section, only then pagination component is shown, otherwise not

Screenshots

  • Pagination component is not visible since number of entries (12) is less than equal to results per page (15)

image

  • Pagination component is visible since number of entries (12) is more than results per page (5)

image

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

  • Bug Fixes
    • Updated the pagination component to prevent rendering when there are not enough items to fill a page.
  • Performance Improvements
    • Simplified the calculation of total doctors in the Facility Staff List by directly using the API response, enhancing performance.

@mnshrm mnshrm requested a review from a team as a code owner November 5, 2024 15:43
Copy link

netlify bot commented Nov 5, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit b92b95c
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/67320e64618f730008d66ec2
😎 Deploy Preview https://deploy-preview-9004--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

coderabbitai bot commented Nov 5, 2024

Walkthrough

The Pagination component in src/components/Common/Pagination.tsx has been updated to modify the condition under which it returns null. The new condition checks if totalCount is either falsy or less than or equal to rowsPerPage, ensuring that the pagination is hidden when there are not enough items to warrant multiple pages. This change enhances the control over the rendering of the pagination component without altering its overall functionality.

Changes

File Change Summary
src/components/Common/Pagination.tsx Updated the condition for returning null to include cases where totalCount is less than or equal to rowsPerPage.
src/components/Facility/FacilityStaffList.tsx Simplified the calculation of totalDoctors by directly assigning data.count instead of iterating over data.results.

Assessment against linked issues

Objective Addressed Explanation
Hide the pagination component if there is only one page. (#8992)

Possibly related PRs

Suggested labels

tested

Suggested reviewers

  • rithviknishad

Poem

In the land of pages, oh so bright,
The Pagination now hides from sight.
When items are few, it knows the way,
To vanish like magic, come what may!
A hop, a skip, no need to display,
Just one page? Then it's time to play! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Member

@rithviknishad rithviknishad left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead let's update the logic in the Pagination component instead that way this behaviour is common for all usages.

const totalCount = data.totalCount;
if (!totalCount) {
return null;
}

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (2)
src/components/Facility/FacilityStaffList.tsx (2)

122-129: LGTM! Consider extracting the condition for better readability.

The conditional rendering logic correctly implements the requirement to show pagination only when needed. The implementation is type-safe with proper null handling.

Consider extracting the condition to a semantic variable name:

+     const shouldShowPagination = (doctorsList?.count ?? 0) > resultsPerPage;
-     {(doctorsList?.count ?? 0) > resultsPerPage && (
+     {shouldShowPagination && (
        <Pagination
          cPage={qParams.page}
          defaultPerPage={resultsPerPage}
          data={{ totalCount: doctorsList?.count ?? 0 }}
          onChange={(page) => updatePage(page)}
        />
      )}

122-129: Consider memoizing the Pagination component to optimize performance.

Since the Pagination component's props only depend on a few values (page, resultsPerPage, count), you could optimize re-renders by memoizing it.

Here's how you could implement this:

const MemoizedPagination = useMemo(
  () => (
    <Pagination
      cPage={qParams.page}
      defaultPerPage={resultsPerPage}
      data={{ totalCount: doctorsList?.count ?? 0 }}
      onChange={(page) => updatePage(page)}
    />
  ),
  [qParams.page, resultsPerPage, doctorsList?.count, updatePage]
);

// Then in your JSX:
{(doctorsList?.count ?? 0) > resultsPerPage && MemoizedPagination}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6b57124 and 69f43da.

📒 Files selected for processing (1)
  • src/components/Facility/FacilityStaffList.tsx (1 hunks)

@nihal467
Copy link
Member

nihal467 commented Nov 6, 2024

image

  • When there are exactly 15 cards—the maximum limit for a single page—the pagination component becomes visible, which shouldn't be the case. Ideally, the pagination component should only appear when there are more than 15 cards, indicating the presence of a second page.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (2)
src/components/Common/Pagination.tsx (2)

Line range hint 6-12: Consider simplifying the component props interface.

The data prop currently only contains totalCount, which could be directly passed as a prop for better clarity and type safety.

Consider this improvement:

 interface PaginationProps {
-  data: { totalCount: number };
+  totalCount: number;
   onChange: (page: number, rowsPerPage: number) => void;
   defaultPerPage: number;
   cPage: number;
   className?: string;
 }

Then update the component usage:

-const totalCount = data.totalCount;
+const totalCount = props.totalCount;

Line range hint 19-20: Optimize state initialization to prevent unnecessary renders.

The rowsPerPage state is initialized to 3 but immediately overridden by defaultPerPage in the useAbortableEffect. Consider initializing it with the defaultPerPage value directly.

-  const [rowsPerPage, setRowsPerPage] = useState(3);
+  const [rowsPerPage, setRowsPerPage] = useState(defaultPerPage);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 69f43da and abfdb83.

📒 Files selected for processing (1)
  • src/components/Common/Pagination.tsx (1 hunks)
🔇 Additional comments (1)
src/components/Common/Pagination.tsx (1)

71-73: LGTM! The pagination visibility logic is now correct.

The updated condition !totalCount || totalCount < rowsPerPage properly handles all cases:

  • Hides pagination when there are no items
  • Hides pagination when items fit in a single page
  • Correctly handles the edge case when total items exactly equal rows per page

Let's verify the component behavior with different scenarios:

✅ Verification successful

Let me analyze the usage patterns to verify the pagination behavior. I'll search for any test files and check the component's implementation details.


Based on the analysis of the codebase, I can now provide a final response regarding the pagination visibility change:

The pagination visibility logic is correctly implemented and consistent with the codebase's requirements.

The verification confirms:

  • The default page sizes across the codebase range from 6 to 36 items (PER_PAGE_LIMIT: 6, RESULTS_PER_PAGE_LIMIT: 14, PAGINATION_LIMIT: 36)
  • Multiple components consistently check if totalCount > PAGINATION_LIMIT before rendering pagination
  • The condition !totalCount || totalCount < rowsPerPage properly handles all cases:
    • Zero items (!totalCount)
    • Items fitting in a single page (totalCount < rowsPerPage)
    • Edge case when total equals page size (correctly hidden)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for test cases or usage patterns of the Pagination component
# to ensure the new condition works as expected in all scenarios.

# Test: Look for test files related to Pagination
fd -e test.tsx -e test.ts -e spec.tsx -e spec.ts Pagination

# Test: Search for Pagination component usage to verify prop patterns
rg -A 3 "<Pagination"

Length of output: 9560


Script:

#!/bin/bash
# Look for default page sizes and pagination limits across the codebase
rg "PAGINATION_LIMIT|PER_PAGE_LIMIT|RESULTS_PER_PAGE|rowsPerPage" -A 2

# Search for Pagination component's implementation details
ast-grep --pattern 'const Pagination = $_' -l typescript

Length of output: 17392

…es/8992/staff-capacity-section-pagination-issue
@github-actions github-actions bot added the Deploy-Failed Deplyment is not showing preview label Nov 6, 2024
@mnshrm
Copy link
Contributor Author

mnshrm commented Nov 6, 2024

Hi @nihal467
I did recheck the fix for 15 entries exactly, Pagination component is not visible in this case as expected, can you please recheck again, I used this facility test-august-secondweek
attaching screenshot for reference
image

@rithviknishad rithviknishad removed the Deploy-Failed Deplyment is not showing preview label Nov 8, 2024
@mnshrm
Copy link
Contributor Author

mnshrm commented Nov 8, 2024

Hi @nihal467,
With the latest commit app is able to correctly render pagination component for FacilityStaffList component, please find the screenshot below. To achieve this ,limit in FacilityStaffList component is changed from 15 to 16, because limit does not take into consideration Total Staff entry which is inserted in doctorList variable by the component before rendering it. Thus limit is updated.
image

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
src/components/Facility/FacilityStaffList.tsx (1)

Line range hint 134-139: Improve pagination component rendering logic.

Consider these improvements for better user experience:

  1. Conditionally render pagination only when doctorsList exists and has results
  2. Add error state handling for doctorsList
-      <Pagination
-        cPage={qParams.page}
-        defaultPerPage={resultsPerPage}
-        data={{ totalCount: doctorsList?.count ?? 0 }}
-        onChange={(page) => updatePage(page)}
-      />
+      {doctorsList?.results?.length > 0 && (
+        <Pagination
+          cPage={qParams.page}
+          defaultPerPage={resultsPerPage}
+          data={{ totalCount: doctorsList.count }}
+          onChange={(page) => updatePage(page)}
+        />
+      )}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b621d66 and 180bdbf.

📒 Files selected for processing (1)
  • src/components/Facility/FacilityStaffList.tsx (1 hunks)
🔇 Additional comments (1)
src/components/Facility/FacilityStaffList.tsx (1)

25-25: ⚠️ Potential issue

Verify the intended page size limit.

The change from 15 to 16 items per page seems inconsistent with the PR objectives and previous discussions about showing pagination only when entries exceed 15 items. This might affect the pagination visibility logic.

Copy link
Contributor Author

@mnshrm mnshrm left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rithviknishad, included the changes as requested

@samholics
Copy link

  • Currently when u add the 16th stafftype pagination will appear without any 2nd page , it better to show the pagination only when the 17th card is updated.
image
  • instead of showing one page's total, it is better to show the total of all pages on the 2nd and 3rd pages also
image
  • when selecting any page from the pagination, the entire page is moving to the top

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (3)
src/components/Facility/FacilityStaffList.tsx (3)

36-36: Consider removing redundant state.

The totalDoctors state appears redundant since doctorsList.count is already available and used for pagination. This creates two sources of truth that could potentially become inconsistent.

Consider using doctorsList?.count directly in the UI instead:

-const [totalDoctors, setTotalDoctors] = useState(0);
// ...
-setTotalDoctors(data.count);
// ...
-<h2 className="mt-2 text-xl font-bold">{totalDoctors}</h2>
+<h2 className="mt-2 text-xl font-bold">{doctorsList?.count ?? 0}</h2>

Line range hint 147-152: Address UX concerns from PR comments.

Several UX issues were mentioned in the PR comments that need attention:

  1. Page scrolls to top when changing pages
  2. Total entries display across all pages

Consider these improvements:

  1. Maintain scroll position on pagination:
    • Wrap the section in a container with fixed height and overflow
    • Use scroll restoration or preserve scroll position on page change
  2. Enhance total entries display:
    • Add "Showing X-Y of Z entries" above or below the pagination

Would you like me to provide implementation examples for these improvements?


Based on the findings, I can now provide the final response:

Pagination implementation needs conditional visibility

The Pagination component already has the correct logic to hide when entries are less than or equal to results per page:

if (!totalCount || totalCount <= rowsPerPage) {
  return null;
}

However, in FacilityStaffList.tsx, the Pagination component is rendered unconditionally. It should be wrapped in a condition to check if doctorsList exists and has results:

{doctorsList && doctorsList.results.length > 0 && (
  <Pagination
    cPage={qParams.page}
    defaultPerPage={resultsPerPage}
    data={{ totalCount: doctorsList?.count ?? 0 }}
    onChange={(page) => updatePage(page)}
  />
)}
🔗 Analysis chain

Line range hint 1-152: Verify complete implementation of PR objectives.

While the basic pagination visibility logic is implemented, there are several items from the PR objectives that need verification or enhancement:

  1. Pagination visibility for exactly 15 entries
  2. Behavior when adding the 16th staff type
  3. Scroll position preservation
  4. Total entries display

Let's verify the implementation against the PR objectives:


Let me generate additional scripts to verify the pagination implementation:


Let me check the Pagination component implementation:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any pagination-related tests
rg -l 'test.*pagination|describe.*pagination'

# Search for scroll-related code
rg 'scroll|overflow'

# Look for staff type addition logic
ast-grep --pattern 'function $_(facilityId) {
  $$$
  doctorsList.results.length
  $$$
}'

Length of output: 41456


Script:

#!/bin/bash
# Search for pagination component implementation
ast-grep --pattern 'function Pagination($props) {
  $$$
}'

# Look for pagination visibility logic in FacilityStaffList
ast-grep --pattern 'const FacilityStaffList = ($props) => {
  $$$
  <Pagination
    $$$
  />
  $$$
}'

# Search for any scroll position management code
rg -A 5 "scrollTo|scrollIntoView" src/components/Facility/

Length of output: 3921


Script:

#!/bin/bash
# Search for Pagination component definition
rg -A 20 "export (default )?function Pagination" src/components/Common/

# Check if there's any conditional rendering of Pagination
rg -A 5 "{.*Pagination" src/components/Facility/FacilityStaffList.tsx

# Look for any totalCount or similar props passed to Pagination
rg "totalCount|data\?: \{" src/components/Common/Pagination.tsx

Length of output: 541

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 582e926 and d016275.

📒 Files selected for processing (1)
  • src/components/Facility/FacilityStaffList.tsx (1 hunks)
🔇 Additional comments (1)
src/components/Facility/FacilityStaffList.tsx (1)

Line range hint 147-152: Verify pagination visibility for edge cases.

Based on the PR comments, there are concerns about pagination visibility when:

  1. Exactly 15 entries are present
  2. The 16th staff type is added

Let's verify the pagination visibility logic:

✅ Verification successful

Pagination visibility behavior is correctly implemented

The implementation in Pagination.tsx correctly handles the edge cases mentioned in the PR comments:

  1. When exactly 15 entries are present (equal to rowsPerPage), the pagination component returns null due to the condition:
if (!totalCount || totalCount <= rowsPerPage) {
  return null;
}
  1. When the 16th staff type is added (exceeding rowsPerPage), the pagination component will be displayed since totalCount > rowsPerPage.

The current implementation matches the expected behavior where pagination should only be visible when there are more items than can fit on a single page.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for the Pagination component's null return condition
ast-grep --pattern 'return null'
# Search for any tests related to pagination visibility
rg -l 'test.*pagination.*visibility|describe.*pagination.*visibility'

Length of output: 2758


Script:

#!/bin/bash
# Let's check the Pagination component's implementation
cat src/components/Common/Pagination.tsx

# Let's also check if there are any specific conditions in FacilityStaffList
cat src/components/Facility/FacilityStaffList.tsx

# Search for any tests related to pagination in general
rg -l "test.*pagination|describe.*pagination"

Length of output: 9943

@mnshrm
Copy link
Contributor Author

mnshrm commented Nov 11, 2024

Hi @samholics,

  • Issue of correct pagination component rendering when entries present are equal to the limit, has been resolved.
  • As for scroll issue, doing any changes to scroll implementation will affect other pages where pagination component is used, fix for this might work on facility page but will hamper user experience on other pages such as assets page, because user will not be taken to the top of the page when page is changed.
  • As for showing the total staff capacity on each page, for this we need to do changes in backend, as we set this value directly from the response received.

…es/8992/staff-capacity-section-pagination-issue
…es/8992/staff-capacity-section-pagination-issue
rithviknishad
rithviknishad previously approved these changes Nov 11, 2024
@rithviknishad rithviknishad dismissed their stale review November 11, 2024 15:26

Just saw other comments

@nihal467
Copy link
Member

nihal467 commented Nov 11, 2024

LGTM , the remaining things can be taken as separate issue

@rithviknishad rithviknishad merged commit 6ab35f1 into ohcnetwork:develop Nov 12, 2024
21 checks passed
Copy link

@mnshrm Your efforts have helped advance digital healthcare and TeleICU systems. 🚀 Thank you for taking the time out to make CARE better. We hope you continue to innovate and contribute; your impact is immense! 🙌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Hide the pagination component in the facility staff capacity section if there is only one page.
5 participants