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

Fixed : User Search Bar #9750

Open
wants to merge 10 commits into
base: develop
Choose a base branch
from

Conversation

Jeffrin2005
Copy link
Contributor

@Jeffrin2005 Jeffrin2005 commented Jan 4, 2025

Proposed Changes

@ohcnetwork/care-fe-code-reviewers

searchbutton.mp4

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

  • New Features

    • Enhanced search functionality for facility users.
    • Improved dynamic querying and filtering of user lists.
    • Updated pagination limit for user results.
    • Implemented a skeleton loading UI for a better user experience during data fetching.
  • Bug Fixes

    • Improved loading state handling for user data display.

@Jeffrin2005 Jeffrin2005 requested a review from a team as a code owner January 4, 2025 17:27
Copy link
Contributor

coderabbitai bot commented Jan 4, 2025

Walkthrough

The pull request modifies the FacilityUsers component to enhance user search functionality. Key changes include updating the useQuery hook to utilize dynamic search parameters, refining the query function to improve user data filtering, and adjusting the loading state handling with a skeleton loading UI for better user experience during data fetching.

Changes

File Change Summary
src/components/Facility/FacilityUsers.tsx - Updated useFilters hook's limit to use RESULTS_PER_PAGE_LIMIT
- Enhanced useQuery hook's queryKey to include qParams
- Modified queryFn to incorporate username, limit, and offset from qParams
- Enhanced loading state with a skeleton UI

Assessment against linked issues

Objective Addressed Explanation
User search functionality [#9741]

Possibly related PRs

Suggested labels

tested, needs review

Suggested reviewers

  • Jacobjeevan
  • bodhish

Poem

🐰 In the search for users, we hop and we play,
With new query magic, we brighten the day.
No more lost names, all results in a line,
Thanks to our coding, the search will now shine!
Hooray for the changes, let’s celebrate cheer,
With every new feature, our vision is clear! ✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f60d1a2 and 92ac884.

📒 Files selected for processing (1)
  • src/components/Facility/FacilityUsers.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Facility/FacilityUsers.tsx

Finishing Touches

  • 📝 Generate Docstrings

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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

netlify bot commented Jan 4, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit a86e895
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/6780109eedfbe80008241681
😎 Deploy Preview https://deploy-preview-9750--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 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

🧹 Nitpick comments (1)
src/components/Facility/FacilityUsers.tsx (1)

40-49: Consider memoizing or debouncing heavy filtering logic.
While the current filtering solution is correct and easy to read, it will re-run every time this component re-renders. For large datasets, you may want to optimize by memoizing the filtered result or debouncing user input.

+// Example of debouncing or using React.useMemo for 'filteredUsers':
+// const filteredUsers = React.useMemo(() => {
+//   const searchString = searchTerm.toLowerCase();
+//   return userListData.results.filter((user) => {
+//     return (
+//       user.username?.toLowerCase().includes(searchString) ||
+//       user.first_name?.toLowerCase().includes(searchString) ||
+//       user.last_name?.toLowerCase().includes(searchString)
+//     );
+//   });
+// }, [searchTerm, userListData.results]);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4850743 and 4080682.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (2)
  • src/components/Facility/FacilityUsers.tsx (3 hunks)
  • src/components/Users/UserListAndCard.tsx (1 hunks)
🔇 Additional comments (7)
src/components/Facility/FacilityUsers.tsx (6)

17-17: Great usage of the filters hook.
No issues identified; the configuration for pagination and cache blacklist looks appropriate.


21-21: State initialization for searchTerm is straightforward.
This is well-implemented and keeps the component logic clean.


36-37: Internationalized “no users found” message.
Returning an i18n-based message is consistent with best practices for multilingual support.


50-50: No direct functional changes here.
No new or updated logic in this line.


52-52: Page component usage is consistent.
Implementation is in line with established project patterns for layout.


62-63: Efficient data flow from parent to child.
Passing the filtered list and controlling the search term state from the parent fosters a clean one-directional data flow. Consider adding a debounce if the user list is large.

src/components/Users/UserListAndCard.tsx (1)

348-348: Good internationalization upgrade.
Replacing hardcoded text with {t("no_users_found")} aligns well with the i18n approach.

@@ -146,8 +146,8 @@
"node": ">=22.8.0"
},
"optionalDependencies": {
"@esbuild/linux-arm64": "*",
Copy link
Member

Choose a reason for hiding this comment

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

Why would you change the lock?

Comment on lines 41 to 51
const filteredUsers = searchTerm
? userListData.results.filter((user) => {
const searchString = searchTerm.toLowerCase();
return (
user.username?.toLowerCase().includes(searchString) ||
user.first_name?.toLowerCase().includes(searchString) ||
user.last_name?.toLowerCase().includes(searchString)
);
})
: userListData.results;

Copy link
Member

Choose a reason for hiding this comment

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

Assume user page has 100 users, your api will only give you 1st 14, this search will only on that 14!!!

@bodhish
Copy link
Member

bodhish commented Jan 4, 2025

Doesn't solve the issue.

@bodhish bodhish closed this Jan 4, 2025
@bodhish bodhish reopened this Jan 4, 2025
@bodhish
Copy link
Member

bodhish commented Jan 4, 2025

You have to pass the search params to the backend and the search should happen at the backend.

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

♻️ Duplicate comments (1)
src/components/Facility/FacilityUsers.tsx (1)

33-40: ⚠️ Potential issue

Current implementation doesn't solve the core search issue

As mentioned in the PR comments by @bodhish, the current implementation only searches through the paginated results (default 18 users) instead of the entire user list. This is a critical limitation that needs to be addressed.

The search should be performed on the server-side across all users. Consider these changes:

  1. Remove client-side filtering
  2. Pass the search parameter to the API
  3. Let the backend handle the search across all users
  4. Return the filtered and paginated results

Example API endpoint structure:

interface SearchParams {
  facility_id: number;
  username?: string;    // Search term
  limit: number;        // Page size
  offset: number;       // Pagination offset
}
🧹 Nitpick comments (5)
src/components/Facility/FacilityUsers.tsx (5)

23-24: Search implementation needs architectural changes

Based on the PR comments, the search functionality should be implemented on the server-side. The current approach of extracting the search parameter locally doesn't fully address this requirement.

Consider implementing these changes:

  1. Ensure the search query is passed to the backend API
  2. Let the backend handle the filtering of all users
  3. Return only the filtered results to the frontend

25-30: Add debouncing to search function

The current implementation triggers an API call on every keystroke, which could lead to performance issues. Consider implementing debouncing to optimize the search functionality.

+ import { debounce } from 'lodash';
+
+ const debouncedSearch = debounce((key: string, value: string) => {
+   updateQuery({
+     ...qParams,
+     [key]: value || undefined,
+   });
+ }, 300);
+
  const handleSearch = (key: string, value: string) => {
-   updateQuery({
-     ...qParams,
-     [key]: value || undefined,
-   });
+   debouncedSearch(key, value);
  };

33-40: Extract hardcoded limit value

The limit value of 18 is duplicated in multiple places. Consider extracting it to a constant to follow the DRY principle.

+ const DEFAULT_PAGE_LIMIT = 18;
+
  const { qParams, updateQuery, Pagination } = useFilters({
-   limit: 18,
+   limit: DEFAULT_PAGE_LIMIT,
    cacheBlacklist: ["username"],
  });
  
  // ... later in the code ...
  queryParams: {
    username,
-   limit: qParams.limit || 18,
-   offset: ((qParams.page || 1) - 1) * (qParams.limit || 18),
+   limit: qParams.limit || DEFAULT_PAGE_LIMIT,
+   offset: ((qParams.page || 1) - 1) * (qParams.limit || DEFAULT_PAGE_LIMIT),
  },

64-65: Improve type safety of search value handling

The empty string fallback could be handled more explicitly to prevent potential undefined behavior.

- searchValue={username || ""}
+ searchValue={typeof username === 'string' ? username : ""}

70-72: Improve pagination condition clarity

The pagination condition uses a hardcoded limit and could be more explicit.

- {userListData.count > (qParams.limit || 18) && (
+ const pageLimit = qParams.limit || DEFAULT_PAGE_LIMIT;
+ {userListData.count > pageLimit && (
    <Pagination totalCount={userListData.count} />
  )}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e624ee3 and aefe830.

📒 Files selected for processing (1)
  • src/components/Facility/FacilityUsers.tsx (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Test
  • GitHub Check: OSSAR-Scan
  • GitHub Check: cypress-run (1)

@Jeffrin2005
Copy link
Contributor Author

@bodhish I passed the search parameters to the backend, but I’m unable to filter. Could you please review my implementation if there’s anything I have missed?

@github-actions github-actions bot added needs-triage question Further information is requested labels Jan 7, 2025
@@ -48,13 +61,15 @@ export default function FacilityUsers(props: { facilityId: number }) {

<UserListView
users={userListData?.results ?? []}
onSearch={(username) => updateQuery({ username })}
searchValue={qParams.username}
onSearch={(username) => handleSearch("username", username)}
Copy link
Contributor

Choose a reason for hiding this comment

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

No need to complicate this:

Suggested change
onSearch={(username) => handleSearch("username", username)}
onSearch={(username) => updateQuery({ username })}

What we had earlier is enough.

src/components/Facility/FacilityUsers.tsx Outdated Show resolved Hide resolved
queryFn: query(routes.facility.getUsers, {
pathParams: { facility_id: facilityId },
queryParams: {
username,
limit: qParams.limit || 18,
Copy link
Contributor

Choose a reason for hiding this comment

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

qParams.limit is enough, no need to add the or.

Same below.

Copy link
Contributor

Choose a reason for hiding this comment

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

Also go ahead and remove the userListLoading check below (line 45); that way enter component isn't refreshing on search.

activeTab={activeTab}
onTabChange={setActiveTab}
/>

<Pagination totalCount={userListData.count} />
{userListData.count > (qParams.limit || 18) && (
Copy link
Contributor

Choose a reason for hiding this comment

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

Pagination will auto handle this, no need for a check.

@Jacobjeevan
Copy link
Contributor

@bodhish I passed the search parameters to the backend, but I’m unable to filter. Could you please review my implementation if there’s anything I have missed?

BE PR.

@Jacobjeevan Jacobjeevan added waiting for backend and removed question Further information is requested needs-triage labels Jan 7, 2025
@github-actions github-actions bot added needs-triage question Further information is requested labels Jan 7, 2025
@Jeffrin2005
Copy link
Contributor Author

Jeffrin2005 commented Jan 7, 2025

@Jacobjeevan Now It is working.

searchbutton.mp4

@Jacobjeevan
Copy link
Contributor

@Jacobjeevan Now It is working.
searchbutton.mp4

Yes, the backend PR was merged 😃

@@ -94,7 +103,7 @@ export default function FacilityUsers(props: { facilityId: number }) {
<UserListView
users={userListData?.results ?? []}
onSearch={(username) => updateQuery({ username })}
searchValue={qParams.username}
searchValue={username || ""}
Copy link
Contributor

Choose a reason for hiding this comment

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

let's not over complicate this, you can just use qParams.username, it will handle it.

queryFn: query(routes.facility.getUsers, {
pathParams: { facility_id: facilityId },
queryParams: {
username,
Copy link
Contributor

@Jacobjeevan Jacobjeevan Jan 7, 2025

Choose a reason for hiding this comment

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

Likewise use qParams.username, no need to de-structure since there's only 2 uses anyways :)

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.

lgtm, keep the lockfile out of the changes though

@rithviknishad rithviknishad requested review from Jacobjeevan, rithviknishad and bodhish and removed request for rithviknishad January 8, 2025 10:37
}),
enabled: !!facilityId,
});

if (userListLoading) {
return <div>Loading...</div>;
return (
Copy link
Contributor

Choose a reason for hiding this comment

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

Let's move this inside the return statement (compare how search functions in this page vs encounters page - we don't wanna re-render everything on page on search).

So, render this if it's loading if not render UserListView.

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Jan 9, 2025
Copy link

github-actions bot commented Jan 9, 2025

👋 Hi, @Jeffrin2005,
Conflicts have been detected against the base branch. Please rebase your branch against the base branch.


This message is automatically generated by prince-chrismc/label-merge-conflicts-action so don't hesitate to report issues/improvements there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
changes required merge conflict pull requests with merge conflict
Projects
None yet
Development

Successfully merging this pull request may close these issues.

User search not working
4 participants