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: Unnecessary API Calls and Re-Renders on Patient Page #9311

Conversation

i0am0arunava
Copy link
Contributor

@i0am0arunava i0am0arunava commented Dec 5, 2024

Proposed Changes

  • Fixes #9308
    prevent Unnecessary API Calls and Re-Renders on Patient Page

@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

  • New Features

    • Introduced a new state variable to optimize API calls and enhance performance.
  • Bug Fixes

    • Improved handling of duplicate patient IDs and refined state management.
  • Refactor

    • Enhanced component structure for clarity and efficiency, reducing unnecessary re-renders.

@i0am0arunava i0am0arunava requested a review from a team as a code owner December 5, 2024 19:55
Copy link
Contributor

coderabbitai bot commented Dec 5, 2024

Walkthrough

The changes in this pull request focus on optimizing the ManagePatients.tsx component by enhancing state management and reducing unnecessary API calls and re-renders. A new state variable paramValue is introduced, which is updated using a useEffect hook that compares current parameters with a previous value stored in a useRef. This comparison helps prevent redundant updates. The API query for fetching patient data is modified to use paramValue, ensuring efficiency in data retrieval while maintaining the existing logic for handling duplicate patient IDs.

Changes

File Change Summary
src/components/Patient/ManagePatients.tsx Added paramValue state variable and previousValueRef for parameter comparison; optimized API calls and re-renders.

Assessment against linked issues

Objective Addressed Explanation
Reduce unnecessary API calls and re-renders on Patient Page (#9308)

Possibly related PRs

Suggested labels

needs testing, needs review, P1

Suggested reviewers

  • rithviknishad
  • shivankacker

Poem

In the code where patients dwell,
Changes made to serve them well.
With fewer calls, the data flows,
A smoother path, as progress shows.
Hopping through the lines of code,
A rabbit's joy in the new abode! 🐇✨


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. (Experiment)
  • @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 Dec 5, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 95903e2
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/6759b90c8071d200089be053
😎 Deploy Preview https://deploy-preview-9311--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

🧹 Outside diff range and nitpick comments (1)
src/components/Patient/ManagePatients.tsx (1)

294-310: Consider optimizing the object comparison implementation.

While the implementation successfully prevents unnecessary updates, it can be improved:

  1. String conversion of values might lead to false positives (e.g., 1 and "1" would be considered equal).
  2. Sorting entries is unnecessary as JSON.stringify maintains key order.

Consider this more efficient implementation:

-function compareObjects(obj1: object, obj2: object) {
-  const entries1 = Object.entries(obj1).map(([key, value]) => [
-    key,
-    String(value),
-  ]);
-  const entries2 = Object.entries(obj2).map(([key, value]) => [
-    key,
-    String(value),
-  ]);
-  entries1.sort(([key1], [key2]) => key1.localeCompare(key2));
-  entries2.sort(([key1], [key2]) => key1.localeCompare(key2));
-  return JSON.stringify(entries1) === JSON.stringify(entries2);
+function compareObjects(obj1: object, obj2: object) {
+  return JSON.stringify(obj1) === JSON.stringify(obj2);
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a24b9ca and f197f25.

📒 Files selected for processing (1)
  • src/components/Patient/ManagePatients.tsx (2 hunks)
🔇 Additional comments (1)
src/components/Patient/ManagePatients.tsx (1)

312-321: LGTM! The implementation successfully prevents unnecessary API calls.

The integration of paramValue with useQuery effectively addresses the issue of unnecessary API calls by ensuring that the query is only triggered when the parameters actually change.

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.

fixed Unnecessary API Calls and Re-Renders on Patient Page

const [paramValue, setParamValue] = useState(params);
const previousValueRef = useRef(params);

function compareObjects(obj1: object, obj2: object) {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

If you console 'params' you observe that two params coming in differently but looking the same were being treated as different values. This was causing unnecessary API calls. Upon examining the previous parameter value and the current incoming parameter value, I found they were different. This issue was occurring not only when typing inside the phone number field but also when changing the option, causing unnecessary API calls.

{page: 1, limit: 12, name: undefined, patient_no: undefined, is_active: 'True', …}
{page: '1', limit: 12, name: undefined, patient_no: undefined, is_active: 'True', …}

If you observe the page key value, the previous one is a number, and the current one is a string. This was the problem. I solved it by comparing two objects while ignoring their value types, which now prevents unnecessary API calls

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.

this is not solving the root cause. this is just hiding the root cause.

the right solution here is to ensure page stays a number, just like the limit does.

@rithviknishad rithviknishad added invalid This doesn't seem right changes required labels Dec 6, 2024
@i0am0arunava
Copy link
Contributor Author

this is not solving the root cause. this is just hiding the root cause.

the right solution here is to ensure page stays a number, just like the limit does.

Got the point

@nihal467
Copy link
Member

nihal467 commented Dec 9, 2024

@i0am0arunava Can you please share the current status of the PR? Otherwise, the PR will be closed in the next 48 hours, and you will be unassigned from the issue due to inactivity.

@i0am0arunava
Copy link
Contributor Author

i0am0arunava commented Dec 9, 2024

@i0am0arunava Can you please share the current status of the PR? Otherwise, the PR will be closed in the next 48 hours, and you will be unassigned from the issue due to inactivity.

@nihal467 @rithviknishad ,I am on leave due to final sem exam from 3rd to 17th December, and it was approved by Arvind . Please don't close this ,I will resume my work after 17th December

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/Patient/ManagePatients.tsx (1)

292-316: Good solution for preventing unnecessary API calls!

The implementation effectively addresses the issue of unnecessary API calls by properly handling type differences in parameter comparisons. However, there are a few optimization opportunities:

  1. The compareObjects function could be more efficient by using useMemo to cache the sorted entries.
  2. Consider using useCallback for the comparison function to prevent recreation on each render.

Here's a suggested optimization:

+ const compareObjects = useCallback((obj1: object, obj2: object) => {
+   const getSortedEntries = useMemo(() => (obj: object) => {
+     return Object.entries(obj)
+       .map(([key, value]) => [key, String(value)])
+       .sort(([key1], [key2]) => key1.localeCompare(key2));
+   }, []);
+ 
+   const entries1 = getSortedEntries(obj1);
+   const entries2 = getSortedEntries(obj2);
+   return JSON.stringify(entries1) === JSON.stringify(entries2);
+ }, []);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f197f25 and ea99582.

📒 Files selected for processing (1)
  • src/components/Patient/ManagePatients.tsx (2 hunks)
🔇 Additional comments (1)
src/components/Patient/ManagePatients.tsx (1)

319-319: LGTM: Proper integration with the optimized state

The modification correctly uses the new paramValue state for API queries, ensuring that the optimization works as intended.

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Dec 12, 2024
Copy link

👋 Hi, @i0am0arunava,
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.

@rithviknishad
Copy link
Member

Completed in #9400

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

Successfully merging this pull request may close these issues.

Unnecessary API Calls and Re-Renders on Patient Page
3 participants