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

Added debouncing for APIs #9801

Conversation

i0am0arunava
Copy link
Contributor

@i0am0arunava i0am0arunava commented Jan 6, 2025

Proposed Changes

@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

Release Notes

  • New Features

    • Added debounce functionality to search inputs across multiple components
    • Implemented internationalization (i18n) support for search placeholders and messages
  • Improvements

    • Optimized search performance by reducing unnecessary API calls
    • Enhanced user feedback with translated search-related messages
  • Localization

    • Added new translation keys for search functionality and organization-related messages
    • Improved support for multilingual user interface

@i0am0arunava i0am0arunava requested a review from a team as a code owner January 6, 2025 18:21
Copy link
Contributor

coderabbitai bot commented Jan 6, 2025

Walkthrough

This pull request introduces a debouncing mechanism for search functionality across multiple components in the application. The changes focus on optimizing API calls by implementing a 500-millisecond delay when users type in search inputs. Additionally, the PR enhances internationalization support by adding translation hooks and updating locale files with new translatable strings for search-related messages and placeholders.

Changes

File Change Summary
src/pages/FacilityOrganization/FacilityOrganizationView.tsx Added debouncing for search, imported translation hook, replaced static text with translatable strings
src/pages/Organization/OrganizationFacilities.tsx Implemented debouncing for query parameters, added translation support, updated input handling
src/pages/Organization/OrganizationView.tsx Added debouncing mechanism for search functionality, imported useDebouncedState hook
public/locale/en.json Added new translation keys for search-related messages and placeholders

Assessment against linked issues

Objective Addressed Explanation
Add debouncing for organization and facility search
Reduce unnecessary network calls on key strokes

Possibly related PRs

Suggested labels

tested, reviewed

Suggested reviewers

  • rithviknishad
  • Jacobjeevan

Poem

🐰 Hop, hop, search with grace,
Debounce magic leaves no trace!
Keys dance slow, API calls neat,
Performance now feels so sweet!
Translations bloom, code takes flight! 🚀


📜 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 a22eaa7 and 4bf3f64.

📒 Files selected for processing (1)
  • public/locale/en.json (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • public/locale/en.json

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 6, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 4bf3f64
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/677f8cc72a384400084cb446
😎 Deploy Preview https://deploy-preview-9801--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/pages/FacilityOrganization/FacilityOrganizationView.tsx (1)

32-34: Adopt consistent naming.

debounceQuery is intuitive, but ensure that references to this function consistently denote debouncing logic across all components to avoid confusion.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6956474 and 6f9e820.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (4)
  • .env (1 hunks)
  • src/pages/FacilityOrganization/FacilityOrganizationView.tsx (4 hunks)
  • src/pages/Organization/OrganizationFacilities.tsx (3 hunks)
  • src/pages/Organization/OrganizationView.tsx (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .env
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (18)
src/pages/FacilityOrganization/FacilityOrganizationView.tsx (5)

3-3: Well-structured import usage.

Bringing in useEffect and useState here is necessary for managing side effects and state in your debouncing setup. This is clear and follows React best practices.


14-15: Good choice of a custom hook for debouncing.

Importing useDebounce indicates that you've encapsulated the debounce logic neatly. This helps keep the component code clean and reusable.


30-30: Ensure proper initialization value for debounced query.

Initializing debouncedQuery to an empty string is appropriate for controlling the initial search state. Just confirm that any dependent functionalities handle the empty string gracefully.


36-38: UseEffect dependencies and cleanup.

Relying on searchQuery in the effect ensures the debouncing triggers only when the user updates the search input, which is correct. However, consider if you need a cleanup or early-cancel mechanism if an API request is in-flight.

Do you want me to propose a diff that handles cancellation of stale promises when the searchQuery changes?


47-47: Perfect alignment between queryKey and query parameters.

Substituting debouncedQuery ensures fewer network calls while typing. Great job ensuring both the queryKey and the queryParams share the same value.

Also applies to: 55-55

src/pages/Organization/OrganizationView.tsx (6)

3-3: Consistent use of React hooks.

Similar to the first file, importing useEffect and useState is essential for implementing debouncing.


14-15: Reusable debouncing solution.

Reusing useDebounce across different components encourages consistency and maintainability.


31-32: Initial debounced state clarity.

Initializing debouncedQuery to an empty string keeps your logic straightforward.


33-36: Naming alignment with prior components.

Using limit and debounceQuery consistently aligns with the prior file’s pattern. Keep an eye on potential naming collisions across the codebase, but here it looks organized.


37-39: Side effect dependencies.

Effect depends on searchQuery. Consider adding a teardown or cancellation to avoid race conditions if the user types very quickly, especially if the API queries are large.


41-41: Search performance improvement.

Replacing direct references to searchQuery with debouncedQuery is exactly what debouncing aims to do. This is an effective optimization.

Also applies to: 47-47

src/pages/Organization/OrganizationFacilities.tsx (7)

3-3: Importing React hooks is consistent.

The addition of useEffect, useState aligns with the rest of the codebase for state and side-effect management.


13-13: Clean separation of concerns by placing the custom debounce hook in "@/hooks/useDebounce".

Keeping custom hooks in a dedicated location improve discoverability and maintainability.


35-36: Debounced parameters for filtering.

Storing a separate debouncedParams state is a good approach, ensuring a stable, debounced version of qParams.


37-40: Well-structured debounce usage.

You use useDebounce to batch user input changes, then update the debounced state in one place. This pattern helps limit network calls.


41-44: JSON.stringify usage in dependencies.

Serializing qParams before comparing changes can help detect deep object diffs. Just be mindful of performance or possible ordering differences—though in practice, it’s commonly used.


46-46: Efficient query key.

Including both id and debouncedParams clarifies caching scope. This is helpful for React Query to handle partial data.


49-53: Debouncing page, offset, and name achieves a uniform approach.

Great to see consistent usage of debounced parameters for pagination and name-based filtering. This helps ensure consistent user experiences across the app.

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.

most of this isn't needed if you use useDebouncedState for the search's state instead of useState

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.

add translations for all these files.

@i0am0arunava
Copy link
Contributor Author

i0am0arunava commented Jan 6, 2025

most of this isn't needed if you use useDebouncedState for the search's state instead of useState

is it okay

  const [debouncedParams, setDebouncedParams] = useDebouncedState(qParams, 500);

    useEffect(() => {
      setDebouncedParams(qParams);
    }, [qParams]);

@github-actions github-actions bot added needs-triage question Further information is requested labels Jan 6, 2025
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: 2

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 97d3e71 and 26a4850.

📒 Files selected for processing (3)
  • src/pages/FacilityOrganization/FacilityOrganizationView.tsx (4 hunks)
  • src/pages/Organization/OrganizationFacilities.tsx (3 hunks)
  • src/pages/Organization/OrganizationView.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/pages/FacilityOrganization/FacilityOrganizationView.tsx
🔇 Additional comments (5)
src/pages/Organization/OrganizationView.tsx (4)

3-3: LGTM! Clean import organization.

The imports are well-organized, separating React core imports, custom hooks, and components.

Also applies to: 14-15


36-38: LGTM! Proper debouncing implementation.

The useEffect hook correctly updates debouncedParams when searchQuery changes, with a reasonable 500ms delay.


31-34: Consider adding error boundaries for the debounced state.

While the debouncing implementation looks good, consider adding error handling for edge cases where the debounced state might fail to update.


43-43: Verify the impact of undefined name parameter.

The code correctly handles empty search by setting name to undefined, but let's verify how the API handles this case.

Also applies to: 49-49

✅ Verification successful

The undefined name parameter is safely handled by React Query

The code uses React Query which automatically handles undefined parameters by omitting them from the request URL. When the name parameter is undefined, it will be excluded from the API request, making this implementation safe and correct.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for API parameter validation
ast-grep --pattern 'name: $_ || undefined' 

Length of output: 44


Script:

#!/bin/bash
# Search for organization children endpoint and parameter handling
ast-grep --pattern 'router.$_("/organizations/$_/children"'

# Also search for any file containing organization children route
rg -l "organizations/.+/children" --type ts

# Look for parameter validation related to organization children
rg "name.*\?" --type ts -A 3 -B 3

Length of output: 40381


Script:

#!/bin/bash
# Search for organization children API endpoint implementation
rg -l "api.*organizations.*children" --type ts

# Look for route handlers or controllers
fd -e ts -e js controller
fd -e ts -e js route

# Search for organization children query implementation
ast-grep --pattern 'router.$_("/organizations/$_/children", async $_'

Length of output: 171

src/pages/Organization/OrganizationFacilities.tsx (1)

13-14: Verify the implementation of useDebouncedState hook.

Let's check the implementation of the custom hook to ensure it handles cleanup and edge cases properly.

✅ Verification successful

The useDebouncedState implementation is well-implemented and safe to use

The hook properly handles cleanup, maintains type safety, and correctly manages debounced state updates through a well-implemented useDebounce hook that includes proper timeout cleanup and edge case handling.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check the implementation of useDebouncedState
rg -A 10 "export.*useDebouncedState" --type ts --type tsx

Length of output: 87


Script:

#!/bin/bash
# First, find the hook file
fd "useDebouncedState\.(ts|tsx)" 

# Then examine its content
rg -A 15 "export.*useDebouncedState"

Length of output: 478


Script:

#!/bin/bash
# Find and examine useDebounce implementation
fd "useDebounce\.(ts|tsx)" 

# Look for useDebounce implementation in case it's in a different file
rg -A 20 "export.*useDebounce" 

Length of output: 1528

const { data: facilities, isLoading } = useQuery({
queryKey: ["organizationFacilities", id, qParams],
queryKey: ["organizationFacilities", id, debouncedParams],
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Update query parameters to match the debouncing split.

If implementing the suggested split of debounced parameters, update the query parameters accordingly.

 queryKey: ["organizationFacilities", id, debouncedParams],
 queryFn: query(routes.facility.list, {
   queryParams: {
-    page: debouncedParams.page,
+    page: qParams.page,
     limit: resultsPerPage,
-    offset: (debouncedParams.page - 1) * resultsPerPage,
+    offset: (qParams.page - 1) * resultsPerPage,
     organization: id,
-    name: debouncedParams.name,
+    name: debouncedSearch || undefined,
     ...advancedFilter.filter,
   },
 }),

Also applies to: 45-49

Comment on lines 35 to 39
const [debouncedParams, setDebouncedParams] = useDebouncedState(qParams, 500);

useEffect(() => {
setDebouncedParams(qParams);
}, [qParams]);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Reconsider debouncing the entire qParams object.

While debouncing works well for search queries, debouncing pagination parameters might lead to a degraded user experience. Consider splitting the debouncing logic to only apply to the search parameters.

-const [debouncedParams, setDebouncedParams] = useDebouncedState(qParams, 500);
+const [debouncedSearch, setDebouncedSearch] = useDebouncedState(qParams.name, 500);

 useEffect(() => {
-  setDebouncedParams(qParams);
+  setDebouncedSearch(qParams.name);
 }, [qParams.name]);

Committable suggestion skipped: line range outside the PR's diff.

@i0am0arunava
Copy link
Contributor Author

add translations for all these files.

@bodhish once told me to make it only for en.json. So, should I make changes only in en.json?

@rithviknishad
Copy link
Member

most of this isn't needed if you use useDebouncedState for the search's state instead of useState

is it okay

  const [debouncedParams, setDebouncedParams] = useDebouncedState(qParams, 500);

    useEffect(() => {
      setDebouncedParams(qParams);
    }, [qParams]);

No, see how other debouncing works in care. For example: ValueSetSelect.

const [search, setSearch] = useDebouncedState("", 500);

@rithviknishad rithviknishad removed question Further information is requested needs-triage labels Jan 7, 2025
@rithviknishad
Copy link
Member

rithviknishad commented Jan 7, 2025

add translations for all these files.

@bodhish once told me to make it only for en.json. So, should I make changes only in en.json?

Refer translation guidelines in README. And add translations for entire files that you've changed.

@i0am0arunava i0am0arunava changed the title Issue/9660/add debouncing for api added debouncing for APIs Jan 7, 2025
@i0am0arunava i0am0arunava changed the title added debouncing for APIs Added debouncing for APIs Jan 7, 2025
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 (2)
src/pages/Organization/OrganizationView.tsx (2)

39-45: Consider adding error handling for the query

While the debounced query integration looks good, consider adding error handling to improve user experience when API calls fail.

 const { data: children, isLoading } = useQuery({
   queryKey: ["organization", id, "children", page, limit, debouncedParams],
+  onError: (error) => {
+    // Handle error appropriately
+    console.error('Failed to fetch organizations:', error);
+  },
   queryFn: query(organizationApi.list, {
     queryParams: {
       parent: id,

Line range hint 31-67: Well-architected debouncing implementation

The overall implementation demonstrates good architectural decisions:

  1. Clear separation between immediate and debounced states
  2. Proper integration with React Query for data fetching
  3. Smooth user experience with loading states
  4. Consistent with the team's discussed approach in the PR comments

Consider documenting this pattern in the project guidelines as it could be useful for other similar implementations.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 26a4850 and 9615a9b.

📒 Files selected for processing (3)
  • src/pages/FacilityOrganization/FacilityOrganizationView.tsx (4 hunks)
  • src/pages/Organization/OrganizationFacilities.tsx (4 hunks)
  • src/pages/Organization/OrganizationView.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/pages/FacilityOrganization/FacilityOrganizationView.tsx
  • src/pages/Organization/OrganizationFacilities.tsx
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test
🔇 Additional comments (3)
src/pages/Organization/OrganizationView.tsx (3)

31-34: Well-implemented debouncing setup!

The 500ms delay is a good balance between responsiveness and performance optimization. The separation of immediate and debounced states allows for a smooth user experience while reducing API calls.


67-67: Good implementation of the search handler!

The handler correctly updates both immediate and debounced states while maintaining proper pagination behavior.


14-14: Verify the implementation of useDebouncedState hook

Let's ensure the custom hook follows React's conventions and handles cleanup properly.

✅ Verification successful

Implementation verified - hooks are well-implemented and safe

The useDebouncedState hook and its dependency useDebounce are properly implemented with:

  • Correct cleanup handling
  • Proper TypeScript typing
  • React hooks best practices
  • Memory leak prevention
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check the implementation of useDebouncedState hook
ast-grep --pattern 'export default function useDebouncedState($_) {
  $$$
}'

Length of output: 78


Script:

#!/bin/bash
# Find the hook file
fd useDebouncedState.ts -t f
fd useDebouncedState.tsx -t f

# If found, display its contents
fd useDebouncedState -t f -x cat {}

Length of output: 675


Script:

#!/bin/bash
# Check the implementation of useDebounce hook
fd useDebounce.ts -t f
fd useDebounce.tsx -t f
fd useDebounce -t f -x cat {}

Length of output: 1333

Copy link
Contributor Author

@i0am0arunava i0am0arunava left a comment

Choose a reason for hiding this comment

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

Is this okay? Can you please check this partially?

@@ -25,16 +27,22 @@ interface Props {
export default function OrganizationView({ id, navOrganizationId }: Props) {
const [page, setPage] = useState(1);
const [searchQuery, setSearchQuery] = useState("");

const [debouncedParams, setDebouncedParams] = useDebouncedState(
Copy link
Contributor Author

Choose a reason for hiding this comment

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

is this okay ?

Copy link
Member

Choose a reason for hiding this comment

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

nope. i don't see any purpose for having two states for debouncing 1 variable

@@ -25,16 +27,22 @@ interface Props {
export default function OrganizationView({ id, navOrganizationId }: Props) {
const [page, setPage] = useState(1);
const [searchQuery, setSearchQuery] = useState("");

const [debouncedParams, setDebouncedParams] = useDebouncedState(
Copy link
Member

Choose a reason for hiding this comment

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

nope. i don't see any purpose for having two states for debouncing 1 variable

@@ -25,16 +27,22 @@ interface Props {
export default function OrganizationView({ id, navOrganizationId }: Props) {
const [page, setPage] = useState(1);
const [searchQuery, setSearchQuery] = useState("");
Copy link
Member

Choose a reason for hiding this comment

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

this should be debounced instead

Copy link
Contributor Author

@i0am0arunava i0am0arunava Jan 8, 2025

Choose a reason for hiding this comment

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

this should be debounced instead

i tried this one but problem is If searchQuery is debounced directly, the input's value={searchQuery} value will lag because the state only updates after the debounce delay

const [searchQuery, setSearchQuery] = useDebouncedState("", 500);

const limit = 12; // 3x4 grid

const { data: children, isLoading } = useQuery({
  queryKey: ["organization", id, "children", page, limit, searchQuery],
  queryFn: query(organizationApi.list, {
    queryParams: {
      parent: id,
      offset: (page - 1) * limit,
      limit,
      name: searchQuery || undefined,
    },
  }),
});

return (
  <Input
    placeholder="Search by name..."
    value={searchQuery}
    onChange={(e) => {
      setSearchQuery(e.target.value);
      setPage(1); // Reset to first page on search
    }}
    className="w-full"
  />
);

To fix this, we need two states but for distinct purposes:

A searchQuery state to handle the immediate user input.
A debounced state (debouncedParams) for triggering the query.

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: 1

🧹 Nitpick comments (2)
src/pages/Organization/OrganizationView.tsx (1)

32-35: Consider consolidating state management

The current implementation maintains two separate states (searchQuery and debouncedParams) for handling the search input. While this works, it could be simplified by using only the debounced state and managing the immediate UI feedback through controlled components.

-const [searchQuery, setSearchQuery] = useState("");
-const [debouncedParams, setDebouncedParams] = useDebouncedState(
-  searchQuery,
-  500,
-);
+const [searchQuery, setSearchQuery] = useDebouncedState("", 500);
src/pages/Organization/OrganizationFacilities.tsx (1)

55-55: Remove debug console.log statement

Debug logging should be removed before merging to production.

-console.log("ddd", debouncedParams);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1afa00d and a22eaa7.

📒 Files selected for processing (3)
  • src/pages/FacilityOrganization/FacilityOrganizationView.tsx (6 hunks)
  • src/pages/Organization/OrganizationFacilities.tsx (7 hunks)
  • src/pages/Organization/OrganizationView.tsx (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/pages/FacilityOrganization/FacilityOrganizationView.tsx
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (5)
src/pages/Organization/OrganizationView.tsx (3)

39-46: LGTM! Effective use of debounced parameters in the query configuration.

The implementation correctly uses debounced parameters in both the query key and query parameters, ensuring that API calls are triggered only after the debounce delay.


62-68: LGTM! Well-implemented search input with translations and proper state management.

The implementation correctly handles:

  • Translated placeholder text
  • Immediate UI feedback
  • Page reset on search
  • Debounced API calls

140-141: LGTM! Proper implementation of translated messages.

The implementation correctly handles both cases with appropriate translations:

  • When search yields no results
  • When there are no sub-organizations
src/pages/Organization/OrganizationFacilities.tsx (2)

67-67: LGTM! Comprehensive implementation of translations

The implementation correctly uses translations for:

  • Search placeholder
  • No results message
  • Action buttons

Also applies to: 110-110, 153-153


38-46: 🛠️ Refactor suggestion

Separate debouncing for search and pagination

Currently, all query parameters including pagination are debounced. This could lead to a degraded user experience as pagination changes should be immediate.

Consider splitting the debouncing logic:

-const [debouncedParams, setDebouncedParams] = useDebouncedState(qParams, 500);
+const [debouncedSearch, setDebouncedSearch] = useDebouncedState(qParams.name, 500);

 const { data: facilities, isLoading } = useQuery({
-  queryKey: ["organizationFacilities", id, debouncedParams],
+  queryKey: ["organizationFacilities", id, qParams.page, debouncedSearch],
   queryFn: query(routes.facility.list, {
     queryParams: {
-      page: debouncedParams.page,
+      page: qParams.page,
       limit: resultsPerPage,
-      offset: (debouncedParams.page - 1) * resultsPerPage,
+      offset: (qParams.page - 1) * resultsPerPage,
       organization: id,
-      name: debouncedParams.name,
+      name: debouncedSearch || undefined,
       ...advancedFilter.filter,
     },
   }),

Likely invalid or redundant comment.

Comment on lines +69 to +75
onChange={(e) => {
updateQuery({
name: e.target.value,
page: 1,
})
}
});
setDebouncedParams({ ...qParams, name: e.target.value, page: 1 });
}}
Copy link
Contributor

@coderabbitai coderabbitai bot Jan 9, 2025

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Update onChange handler to match separated debouncing

The onChange handler should be updated to match the separated debouncing logic for search and pagination.

 onChange={(e) => {
   updateQuery({
     name: e.target.value,
     page: 1,
   });
-  setDebouncedParams({ ...qParams, name: e.target.value, page: 1 });
+  setDebouncedSearch(e.target.value);
 }}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
onChange={(e) => {
updateQuery({
name: e.target.value,
page: 1,
})
}
});
setDebouncedParams({ ...qParams, name: e.target.value, page: 1 });
}}
onChange={(e) => {
updateQuery({
name: e.target.value,
page: 1,
});
setDebouncedSearch(e.target.value);
}}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Update onChange handler to match separated debouncing

The onChange handler should be updated to match the separated debouncing logic for search and pagination.

 onChange={(e) => {
   updateQuery({
     name: e.target.value,
     page: 1,
   });
-  setDebouncedParams({ ...qParams, name: e.target.value, page: 1 });
+  setDebouncedSearch(e.target.value);
 }}

📝 Committable suggestion

no ,can not do this , this will return type error Argument of type 'string' is not assignable to parameter of type 'SetStateAction<QueryParam>'.ts(2345)

Copy link
Contributor

Choose a reason for hiding this comment

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

@i0am0arunava You're absolutely right. I apologize for the incorrect suggestion. Your current implementation using setDebouncedParams with the full query params object is the correct approach as it maintains proper TypeScript type safety. Please keep the existing implementation.

:thinking_face:
⟪ ⬚⬚⬚⬚⬚⬚⬚ ⟫
⟪ ⬚🐰⬚⬚⬚⬚⬚ ⟫
⟪ ⬚⬚⬚⬚⬚⬚⬚ ⟫


✏️ Learnings added
Learnt from: i0am0arunava
PR: ohcnetwork/care_fe#9801
File: src/pages/Organization/OrganizationFacilities.tsx:69-75
Timestamp: 2025-01-09T08:56:20.006Z
Learning: When using useDebouncedState with query parameters in TypeScript, ensure the debounced state maintains the same type as the original state (QueryParam). Avoid splitting into separate string states as it breaks type safety.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

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.

  1. Not a fan of how debouncing is achieved here by introducing a new state and all... See Adds query.debounced and updated queries that require debouncing #9865 on how it's achieved.

  2. this does not cover most of the places where debouncing is required. you could've tried a regex search to somewhat get a larger collection of queries that require debouncing

image

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.

Add debouncing for all new API's
3 participants