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

Integrates useInfiniteQuery for data fetching and resolves Infinite Load issue in Notes. #9190

Conversation

JavidSumra
Copy link
Contributor

@JavidSumra JavidSumra commented Nov 23, 2024

Proposed Changes

@ohcnetwork/care-fe-code-reviewers


Merge Checklist

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

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced patient notes functionality with improved state management and pagination.
    • Introduced a new hook for adding patient notes, streamlining the note addition process.
  • Bug Fixes

    • Adjusted loading state handling for better user experience during data fetching.
  • Refactor

    • Simplified data fetching logic across multiple components.
    • Replaced manual pagination handling with a more efficient approach using hooks.
    • Updated component interfaces to reflect changes in state management and properties.
    • Removed unnecessary properties from state structures to streamline data handling.
    • Improved handling of note addition and state resets in various components.
    • Streamlined the interface of components by removing redundant props.
    • Enhanced re-rendering behavior by introducing unique keys based on patient ID and thread.

@JavidSumra JavidSumra requested a review from a team as a code owner November 23, 2024 07:19
Copy link
Contributor

coderabbitai bot commented Nov 23, 2024

Walkthrough

The pull request introduces significant refactoring across multiple patient notes and consultation components. The primary focus is on implementing infinite scrolling using React Query's useInfiniteQuery hook, removing manual pagination logic, and simplifying state management. Components like PatientConsultationNotesList, PatientNotesList, and others have been updated to use the new query hook, eliminating previous manual data fetching methods and streamlining the code structure.

Changes

File Change Summary
src/components/Facility/PatientConsultationNotesList.tsx Replaced manual data fetching with useInfiniteQuery, simplified loading state management
src/components/Facility/PatientNotesList.tsx Migrated to useInfiniteQuery, improved data retrieval and pagination handling
src/components/Facility/ConsultationDoctorNotes/index.tsx Removed cPage and totalPages, added useAddPatientNote mutation
src/components/Facility/PatientNoteCard.tsx Integrated useQuery for edit history, removed setReload prop
src/components/Patient/PatientDetailsTab/Notes.tsx Refactored note addition using useAddPatientNote mutation
src/components/Patient/PatientNotes.tsx Integrated useAddPatientNote hook for note addition
src/components/Facility/DoctorNote.tsx Added hasMore prop for infinite scrolling
src/components/Facility/PatientNotesSlideover.tsx Updated note addition and thread changing logic
src/components/Facility/models.tsx Removed cPage and totalPages from PatientNoteStateType
src/components/Patient/Utils.ts Added useAddPatientNote custom hook
cypress/e2e/patient_spec/PatientDoctorNotes.cy.ts Simplified test case for nurse notes by removing success message verification

Assessment against linked issues

Objective Addressed Explanation
Enhance Discussion Notes Chat History Implemented infinite scrolling using React Query
Prevent Unexpected Page Reloads Replaced manual pagination with useInfiniteQuery hook
Smooth Scrolling Experience Added hasMore prop and improved data fetching mechanism

Possibly related PRs

Suggested Reviewers

  • rithviknishad
  • nihal467
  • Jacobjeevan

Poem

🐰 Scrolling notes with grace and might,
Infinite queries, a developer's delight!
React Query dances, pagination takes flight,
Code refactored, everything feels just right!
Rabbit's code hops, clean and bright! 🚀


📜 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 957cd60 and b967c97.

📒 Files selected for processing (1)
  • src/components/Facility/ConsultationDoctorNotes/index.tsx (5 hunks)
🧰 Additional context used
📓 Learnings (1)
src/components/Facility/ConsultationDoctorNotes/index.tsx (1)
Learnt from: UdaySagar-Git
PR: ohcnetwork/care_fe#9298
File: src/components/Facility/PatientNotesDetailedView.tsx:147-188
Timestamp: 2024-12-05T22:41:24.173Z
Learning: In the `PatientNotesDetailedView` component, child notes (`state.child_notes`) are fetched along with the parent note in a single query, so a separate loading state for child notes is not required.
🔇 Additional comments (7)
src/components/Facility/ConsultationDoctorNotes/index.tsx (7)

Line range hint 1-27: LGTM! Clean migration to React Query.

The import changes appropriately reflect the migration from manual API calls to React Query hooks.


93-97: LGTM! Robust data handling.

The useEffect properly handles undefined data with appropriate fallbacks.


145-152: LGTM! Clean thread switching logic.

The state reset on thread change is properly implemented, ensuring a clean slate for the new thread.


159-159: LGTM! Proper key implementation.

The key combination ensures proper component remounting when patient or thread changes.


Line range hint 100-111: Optimize real-time update strategy.

Setting reload to true on every message might cause unnecessary rerenders. Consider using React Query's invalidation instead.

 useMessageListener((data) => {
   const message = data?.message;
   if (
     (message?.from == "patient/doctor_notes/create" ||
       message?.from == "patient/doctor_notes/edit") &&
     message?.facility_id == facilityId &&
     message?.patient_id == patientId
   ) {
-    setReload(true);
+    queryClient.invalidateQueries({ 
+      queryKey: ["patient", patientId, thread] 
+    });
   }
 });

63-82: 🛠️ Refactor suggestion

Add error handling to mutation.

The note submission lacks error handling. Consider adding onError callback to handle API failures gracefully.

 const { mutate: addNote } = useAddPatientNote({
   patientId,
   thread,
   consultationId,
+  onError: (error) => {
+    Notification.Error({
+      msg: t("error_adding_note"),
+    });
+  },
 });

Likely invalid or redundant comment.


86-91: Consider adding thread to queryKey for proper cache invalidation.

Based on previous discussions, the thread parameter might be needed in the queryKey for proper cache management.

-    queryKey: ["patient", patientId],
+    queryKey: ["patient", patientId, thread],

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 Nov 23, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit b967c97
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/676e250f2c5c3e0008d46e4f
😎 Deploy Preview https://deploy-preview-9190--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: 3

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

Line range hint 1-105: Consider implementing a more robust infinite scroll solution

The current implementation might benefit from using established infinite scroll libraries or implementing virtual scrolling to handle large datasets more efficiently.

Consider these architectural improvements:

  1. Use a virtual scroll library like react-window or react-virtualized to efficiently render large lists
  2. Implement scroll position restoration using ScrollRestoration from react-router-dom
  3. Add loading states for individual batches to show progress without full-screen loading
  4. Consider implementing a cursor-based pagination instead of offset-based to prevent issues with concurrent updates

Example implementation structure:

import { FixedSizeList } from 'react-window';

interface NotesListProps {
  // ... existing props
  windowHeight: number;
}

const NotesListRow = ({ index, style, data }) => {
  const note = data.notes[index];
  return (
    <div style={style}>
      <DoctorNote note={note} />
    </div>
  );
};

const PatientNotesList = (props: NotesListProps) => {
  const [scrollOffset, setScrollOffset] = useState(0);
  
  // ... existing state and effects

  return (
    <FixedSizeList
      height={props.windowHeight}
      itemCount={state.notes.length}
      itemSize={120}
      onScroll={({ scrollOffset }) => {
        setScrollOffset(scrollOffset);
        // Trigger load more when near bottom
      }}
    >
      {NotesListRow}
    </FixedSizeList>
  );
};
src/components/Facility/PatientConsultationNotesList.tsx (1)

Line range hint 41-77: Enhance infinite scroll implementation to prevent unexpected reloads

The current implementation might be causing the reported issues with unexpected reloads and lost scroll position. Several improvements are recommended:

  1. The scroll position issue mentioned in Enhance Discussion Notes Chat History with Infinite Scrolling or Better Navigation Solution #9188 likely occurs because state updates trigger re-renders without preserving scroll position.
  2. Multiple rapid scroll events could trigger unnecessary fetches.
  3. The loading state might cause layout shifts during updates.

Consider these improvements:

  1. Implement scroll position preservation:
const scrollRef = useRef<HTMLDivElement>(null);
const scrollPosition = useRef(0);

const saveScrollPosition = () => {
  if (scrollRef.current) {
    scrollPosition.current = scrollRef.current.scrollTop;
  }
};

const restoreScrollPosition = () => {
  if (scrollRef.current) {
    scrollRef.current.scrollTop = scrollPosition.current;
  }
};

// Save position before fetch
saveScrollPosition();
fetchNotes().then(() => {
  setIsLoading(false);
  setReload?.(false);
  // Restore position after state update
  requestAnimationFrame(restoreScrollPosition);
});
  1. Add debouncing to prevent rapid fetches:
const debouncedHandleNext = useMemo(
  () => debounce(() => {
    if (state.cPage < state.totalPages) {
      setState((prevState) => ({
        ...prevState,
        cPage: prevState.cPage + 1,
      }));
      setReload?.(true);
    }
  }, 250),
  [state.cPage, state.totalPages]
);
  1. Consider using a virtual scroll library like react-window for better performance with large lists.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2fdffa2 and af6ff98.

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

67-68: 🛠️ Refactor suggestion

Verify scroll position preservation during thread changes

Setting both loading and reload states simultaneously on thread change might cause scroll position loss, which was mentioned as a key issue in the original bug report.

Let's verify the scroll handling in related components:

Consider debouncing the reload trigger and preserving scroll position:

  useEffect(() => {
+   const currentScrollPosition = window.scrollY;
    setIsLoading(true);
-   setReload(true);
+   // Debounce reload to prevent rapid re-fetches
+   const timeoutId = setTimeout(() => {
+     setReload(true);
+   }, 100);
+   // Restore scroll position after state updates
+   requestAnimationFrame(() => {
+     window.scrollTo(0, currentScrollPosition);
+   });
+   return () => clearTimeout(timeoutId);
  }, [thread]);
src/components/Facility/PatientConsultationNotesList.tsx (1)

Line range hint 1-1: Verify similar scroll handling in related components

Let's check if similar infinite scroll patterns exist in other components that might need the same improvements.

src/components/Facility/PatientNotesList.tsx Outdated Show resolved Hide resolved
src/components/Facility/PatientConsultationNotesList.tsx Outdated Show resolved Hide resolved
src/components/Facility/PatientConsultationNotesList.tsx Outdated Show resolved Hide resolved
Copy link
Member

@yash-learner yash-learner left a comment

Choose a reason for hiding this comment

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

LGTM

@nihal467
Copy link
Member

LGTM

@nihal467
Copy link
Member

nihal467 commented Dec 4, 2024

@JavidSumra what is the status on this PR

@JavidSumra
Copy link
Contributor Author

Hey @nihal467 I'm working on useInfiniteQuery hook so need some time.

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

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

63-68: ⚠️ Potential issue

Add error handling to mutation

The mutation lacks error handling for API failures.

Add error handling to the mutation:

  const { mutate: addNote } = useAddPatientNote({
    patientId,
    thread,
    consultationId,
+   onError: (error) => {
+     Notification.Error({
+       msg: "Failed to add note. Please try again.",
+     });
+   },
  });
🧹 Nitpick comments (3)
src/components/Facility/ConsultationDoctorNotes/index.tsx (3)

94-99: Consider using data destructuring for cleaner state updates

The effect can be simplified using object destructuring.

-  useEffect(() => {
-    setPatientActive(data?.is_active ?? true);
-    setPatientName(data?.name ?? "");
-    setFacilityName(data?.facility_object?.name ?? "");
-  }, [data]);
+  useEffect(() => {
+    const { is_active = true, name = "", facility_object } = data ?? {};
+    setPatientActive(is_active);
+    setPatientName(name);
+    setFacilityName(facility_object?.name ?? "");
+  }, [data]);

69-82: Consider optimistic updates for better UX

The note addition could benefit from optimistic updates to improve user experience.

Consider updating the local state optimistically before the API call completes:

const optimisticNote = {
  id: 'temp-' + Date.now(),
  note: noteField,
  created_date: new Date().toISOString(),
  created_by: authUser,
  // ... other required fields
};

addNote(
  { note: noteField, reply_to: reply_to?.id, thread },
  {
    onMutate: async () => {
      await queryClient.cancelQueries(["/patient", patientId, thread]);
      const previousNotes = queryClient.getQueryData(["/patient", patientId, thread]);
      queryClient.setQueryData(["/patient", patientId, thread], old => ({
        ...old,
        notes: [optimisticNote, ...old.notes]
      }));
      return { previousNotes };
    },
    onError: (err, variables, context) => {
      queryClient.setQueryData(["/patient", patientId, thread], context.previousNotes);
    }
  }
);

146-153: Optimize tab click handler

The tab click handler could be memoized to prevent unnecessary re-renders.

+ const handleTabClick = useCallback((selectedThread: string) => {
+   if (thread !== selectedThread) {
+     setThread(selectedThread);
+     setState(initialData);
+     setReplyTo(undefined);
+     setNoteField("");
+   }
+ }, [thread, initialData]);

  // In JSX:
- onClick={() => {
-   if (thread !== PATIENT_NOTES_THREADS[current]) {
-     setThread(PATIENT_NOTES_THREADS[current]);
-     setState(initialData);
-     setReplyTo(undefined);
-     setNoteField("");
-   }
- }}
+ onClick={() => handleTabClick(PATIENT_NOTES_THREADS[current])}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 25a2b5f and 957cd60.

📒 Files selected for processing (2)
  • cypress/e2e/patient_spec/PatientDoctorNotes.cy.ts (0 hunks)
  • src/components/Facility/ConsultationDoctorNotes/index.tsx (5 hunks)
💤 Files with no reviewable changes (1)
  • cypress/e2e/patient_spec/PatientDoctorNotes.cy.ts
🧰 Additional context used
📓 Learnings (1)
src/components/Facility/ConsultationDoctorNotes/index.tsx (1)
Learnt from: UdaySagar-Git
PR: ohcnetwork/care_fe#9298
File: src/components/Facility/PatientNotesDetailedView.tsx:147-188
Timestamp: 2024-12-05T22:41:24.173Z
Learning: In the `PatientNotesDetailedView` component, child notes (`state.child_notes`) are fetched along with the parent note in a single query, so a separate loading state for child notes is not required.
🔇 Additional comments (2)
src/components/Facility/ConsultationDoctorNotes/index.tsx (2)

1-1: Consider adding more specific query keys

The query key structure could be more specific to prevent unintended cache invalidations.

Consider adding the route name to the query key for better cache management:

-    queryKey: ["/patient", patientId, thread],
+    queryKey: ["patient", routes.getPatient, patientId, thread],

Also applies to: 17-17, 27-27


160-160: LGTM: Key prop addition

The key prop addition ensures proper component remounting when thread or patientId changes.

src/components/Facility/ConsultationDoctorNotes/index.tsx Outdated Show resolved Hide resolved
@rithviknishad rithviknishad added invalid This doesn't seem right and removed needs review tested merge conflict pull requests with merge conflict labels Dec 27, 2024
@rithviknishad rithviknishad added needs testing and removed invalid This doesn't seem right labels Dec 27, 2024
@nihal467
Copy link
Member

LGTM

@Jacobjeevan Jacobjeevan merged commit 94585fd into ohcnetwork:develop Dec 29, 2024
27 checks passed
Copy link

@JavidSumra 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
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Enhance Discussion Notes Chat History with Infinite Scrolling or Better Navigation Solution
7 participants