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

Fix Inifinite Load issue in notes #9190

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

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

  • New Features

    • Improved loading state management for patient consultation and notes lists, ensuring a smoother user experience during data fetching.
  • Bug Fixes

    • Resolved issues with loading state not accurately reflecting the data fetching process, enhancing reliability when fetching patient notes.

@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 changes made in this pull request focus on improving the loading state management and control flow within the PatientConsultationNotesList and PatientNotesList components. The loading state is now set to false only after the notes have been successfully fetched, enhancing the clarity of the asynchronous data fetching process. Additionally, the handling of the reload state has been adjusted to ensure it is set appropriately before fetching notes, providing a more streamlined user experience.

Changes

File Path Change Summary
src/components/Facility/PatientConsultationNotesList.tsx Modified loading state management in fetchNotes to set loading state only after notes are fetched. Adjusted useEffect to set loading state to true before fetching notes.
`src/components/Facility/PatientNotesList.tsx Similar modifications to loading state management and reload functionality during fetching of patient notes.

Assessment against linked issues

Objective Addressed Explanation
Enhance scrolling experience in Discussion Notes section (#9188) Changes do not address the scrolling issue or navigation experience.

Possibly related PRs

Suggested labels

needs testing, needs review, P1

Suggested reviewers

  • sainak
  • rithviknishad
  • shivankacker

🐰 In the land of notes, where patients reside,
A loading state shift, we take in our stride.
With fetch now more clear, and reloading just right,
Our users will smile, as they scroll through the night!
🌙✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint (1.23.1)

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

src/components/Facility/PatientConsultationNotesList.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

Error: Failed to load parser '@typescript-eslint/parser' declared in '.eslintrc.json': Cannot find module '@typescript-eslint/parser'
Require stack:

  • /.eslintrc.json
    at Module._resolveFilename (node:internal/modules/cjs/loader:1248:15)
    at Function.resolve (node:internal/modules/helpers:145:19)
    at Object.resolve (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:2346:46)
    at ConfigArrayFactory._loadParser (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3325:39)
    at ConfigArrayFactory._normalizeObjectConfigDataBody (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3099:43)
    at _normalizeObjectConfigDataBody.next ()
    at ConfigArrayFactory._normalizeObjectConfigData (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3040:20)
    at _normalizeObjectConfigData.next ()
    at ConfigArrayFactory.loadInDirectory (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:2886:28)
    at CascadingConfigArrayFactory._loadConfigInAncestors (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3871:46)

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

netlify bot commented Nov 23, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit af6ff98
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/674181f2c2ebce0008c52833
😎 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.

Comment on lines +59 to +62
fetchNotes().then(() => {
setIsLoading(false);
setReload(false);
});
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

Consider adding error handling and preventing race conditions

While moving state updates into Promise.then() is good, we should handle errors and prevent race conditions during concurrent fetches.

Consider this improvement:

-      fetchNotes().then(() => {
-        setIsLoading(false);
-        setReload(false);
-      });
+      let isMounted = true;
+      fetchNotes()
+        .then(() => {
+          if (isMounted) {
+            setIsLoading(false);
+            setReload(false);
+          }
+        })
+        .catch((error) => {
+          if (isMounted) {
+            console.error('Failed to fetch notes:', error);
+            setIsLoading(false);
+            setReload(false);
+          }
+        });
+      return () => {
+        isMounted = false;
+      };

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

Comment on lines +74 to +77
fetchNotes().then(() => {
setIsLoading(false);
setReload?.(false);
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling to prevent UI from being stuck in loading state

While moving the loading state update to the promise resolution is good, we should also handle errors to prevent the UI from being stuck in a loading state if the fetch fails.

Consider adding error handling:

 fetchNotes().then(() => {
   setIsLoading(false);
   setReload?.(false);
-});
+}).catch((error) => {
+  setIsLoading(false);
+  setReload?.(false);
+  // Consider adding error state management here
+});
📝 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
fetchNotes().then(() => {
setIsLoading(false);
setReload?.(false);
});
fetchNotes().then(() => {
setIsLoading(false);
setReload?.(false);
}).catch((error) => {
setIsLoading(false);
setReload?.(false);
// Consider adding error state management here
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
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
1 participant