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

BA-2081: chat rooms refetch issue #182

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

Conversation

pt-tsl
Copy link
Contributor

@pt-tsl pt-tsl commented Jan 14, 2025

Acceptance Criteria
Given I have 10 chats in my active chat list, when I switch to another Chat List Tab and come back to the Active Chat list. I should still be able to see and access the 10 original chat rooms

https://www.loom.com/share/8714eef222ea48b193593d9f36b0496d?sid=a162b289-d22f-49c7-8dec-efd9240b755e

Approvd
https://app.approvd.io/silverlogic/BA/stories/38025

Summary by CodeRabbit

  • New Features
    • Enhanced chat rooms list rendering with improved data fetching.
    • Added conditional rendering for empty states in the chat rooms list.
    • Improved responsiveness to data changes for the chat rooms list.
    • Introduced a new state variable for controlled rendering of the chat rooms list.

Copy link

changeset-bot bot commented Jan 14, 2025

⚠️ No Changeset found

Latest commit: a96ed0f

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link

coderabbitai bot commented Jan 14, 2025

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

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.

packages/components/modules/messages/ChatRoomsList/index.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

Error: Cannot read config file: /packages/components/.eslintrc.js
Error: Cannot find module '@baseapp-frontend/config/.eslintrc.js'
Require stack:

  • /packages/components/.eslintrc.js
  • /node_modules/.pnpm/@eslint[email protected]/node_modules/@eslint/eslintrc/dist/eslintrc.cjs
  • /node_modules/.pnpm/[email protected]/node_modules/eslint/lib/cli-engine/cli-engine.js
  • /node_modules/.pnpm/[email protected]/node_modules/eslint/lib/eslint/eslint.js
  • /node_modules/.pnpm/[email protected]/node_modules/eslint/lib/eslint/index.js
  • /node_modules/.pnpm/[email protected]/node_modules/eslint/lib/cli.js
  • /node_modules/.pnpm/[email protected]/node_modules/eslint/bin/eslint.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1248:15)
    at Module._load (node:internal/modules/cjs/loader:1074:27)
    at TracingChannel.traceSync (node:diagnostics_channel:315:14)
    at wrapModuleLoad (node:internal/modules/cjs/loader:217:24)
    at Module.require (node:internal/modules/cjs/loader:1339:12)
    at require (node:internal/modules/helpers:135:16)
    at Object. (/packages/components/.eslintrc.js:1:18)
    at Module._compile (node:internal/modules/cjs/loader:1546:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1691:10)
    at Module.load (node:internal/modules/cjs/loader:1317:32)

Walkthrough

The pull request introduces a new state variable renderList in the ChatRoomsList component, which controls the rendering of the chat rooms list. The handleSearchChange, handleSearchClear, and handleChange functions are updated to use a fetchPolicy of 'network-only' to ensure fresh data is fetched from the server. A new useEffect hook is added to reset renderList when data changes, enhancing the conditional rendering logic for empty states in the chat rooms list.

Changes

File Change Summary
packages/components/modules/messages/ChatRoomsList/index.tsx Added renderList state to control rendering, updated handleSearchChange, handleSearchClear, and handleChange to use fetchPolicy: 'network-only', added useEffect for renderList, and modified rendering logic in renderListContent for empty states.

Possibly related PRs

Suggested reviewers

  • Ronan-Fernandes
  • anicioalexandre

Poem

🐰 In the chat room's lively space,
A list appears, a friendly face.
With fresh data, we take a glance,
Empty states? We’ll find our chance!
Rendering joy, with every trace! 🌟

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.

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

@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

🔭 Outside diff range comments (1)
packages/components/modules/messages/ChatRoomsList/index.tsx (1)

Reset cursor when switching tabs to ensure proper pagination

The cursor should be reset when switching tabs because each tab (unread/archived) represents a distinct dataset. Using a cursor from one tab's context for another tab's query could lead to incorrect pagination results.

The suggested implementation is correct:

 const handleChange = (event: React.SyntheticEvent, newTab: string) => {
   setTab(newTab as ChatTabValues)
+  cursor.current = null
   startRefetchTransition(() => {
     refetch(
       {
         unreadMessages: newTab === CHAT_TAB_VALUES.unread,
         archived: newTab === CHAT_TAB_VALUES.archived,
-        cursor: cursor.current,
       },
       { fetchPolicy: 'store-and-network' },
     )
   })
 }
🔗 Analysis chain

Line range hint 70-80: Verify cursor handling during tab switches.

While the cursor is correctly passed to refetch, consider if the cursor should be reset when switching tabs to ensure fresh data fetching.

Consider this implementation:

 const handleChange = (event: React.SyntheticEvent, newTab: string) => {
   setTab(newTab as ChatTabValues)
+  cursor.current = null
   startRefetchTransition(() => {
     refetch(
       {
         unreadMessages: newTab === CHAT_TAB_VALUES.unread,
         archived: newTab === CHAT_TAB_VALUES.archived,
-        cursor: cursor.current,
       },
       { fetchPolicy: 'store-and-network' },
     )
   })
 }

Let's verify the current behavior:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for similar pagination implementations in the codebase
ast-grep --pattern 'refetch($_, { fetchPolicy: $_ })'

Length of output: 937


Script:

#!/bin/bash
# Search for cursor usage in state and refs
ast-grep --pattern 'const cursor = useRef'

# Search for pagination-related patterns
ast-grep --pattern 'const [$_] = usePagination'

# Look for cursor reset patterns
rg "cursor.*null" -A 2

Length of output: 7142

🧹 Nitpick comments (1)
packages/components/modules/messages/ChatRoomsList/index.tsx (1)

48-48: Consider maintaining separate cursors per tab.

To improve the pagination state management, consider maintaining separate cursors for each tab. This would prevent pagination state interference between tabs and provide a better user experience.

Example implementation:

const cursors = useRef<Record<ChatTabValues, string | null>>({
  [CHAT_TAB_VALUES.active]: null,
  [CHAT_TAB_VALUES.unread]: null,
  [CHAT_TAB_VALUES.archived]: null
})
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2692120 and 44e22f6a90330527cc0b2766dd7314b0b4c23b8e.

📒 Files selected for processing (1)
  • packages/components/modules/messages/ChatRoomsList/index.tsx (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (2)
packages/components/modules/messages/ChatRoomsList/index.tsx (2)

3-11: LGTM! Clean import organization.

The addition of useRef is properly grouped with other React hooks.


48-48: LGTM! Well-typed cursor reference.

The cursor ref is properly typed to handle all possible states and appropriately initialized.

@tsl-ps2
Copy link
Collaborator

tsl-ps2 commented Jan 14, 2025

I am slightly confused, can you explain how this works? It looks to me like cursor.current does not change after its first initialization (its value is persisted between calls and updated only when it is null or undefined). But that means that cursor.current always points to the last entry (?) of the first chat room page in the 'Active' tab? When changing tabs, we always refetch from that entry? Doesn't that break proper refetching of the unread and archived tabs, and also of the active tab in case the chatrooms change order on new messages?

Copy link
Collaborator

@anicioalexandre anicioalexandre left a comment

Choose a reason for hiding this comment

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

should we double check the other refetches we have on messages as well?

@pt-tsl pt-tsl force-pushed the BA-2081-dissapearing-chats branch 2 times, most recently from cf402b1 to ec67947 Compare January 15, 2025 15:35
@pt-tsl pt-tsl force-pushed the BA-2081-dissapearing-chats branch from a96ed0f to 3635abb Compare February 5, 2025 11:41
Copy link

sonarqubecloud bot commented Feb 5, 2025

Copy link

@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 (1)
packages/components/modules/messages/ChatRoomsList/index.tsx (1)

215-219: Consider memoizing the endReached callback.

The endReached callback is recreated on every render. Consider memoizing it with useCallback to optimize performance.

+ const handleEndReached = useCallback(() => {
+   if (hasNext) {
+     loadNext(5)
+   }
+ }, [hasNext, loadNext])

  return (
    <ChatRoomListContainer>
      {/* ... */}
      {renderList && (
        <Virtuoso
          {/* ... */}
-         endReached={() => {
-           if (hasNext) {
-             loadNext(5)
-           }
-         }}
+         endReached={handleEndReached}
          {...VirtuosoProps}
        />
      )}
    </ChatRoomListContainer>
  )
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a96ed0f and 3635abb.

📒 Files selected for processing (1)
  • packages/components/modules/messages/ChatRoomsList/index.tsx (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Lint
  • GitHub Check: Component Test Applications and Packages
🔇 Additional comments (2)
packages/components/modules/messages/ChatRoomsList/index.tsx (2)

3-41: LGTM! Clean state management addition.

The new renderList state is well-integrated and follows React conventions.


97-102: Consider tracking the Virtuoso bug.

The workaround is well-documented, but it would be beneficial to track the upstream Virtuoso issue for a proper fix in the future.

Could you share the Virtuoso issue number? If not, consider creating one to track this workaround.

Comment on lines 54 to 95
const handleSearchChange: ChangeEventHandler<HTMLInputElement> = (e) => {
const value = e.target.value || ''
startTransition(() => {
refetch({
q: value,
unreadMessages: isInUnreadTab,
archived: isInArchivedTab,
})
refetch(
{
q: value,
unreadMessages: isInUnreadTab,
archived: isInArchivedTab,
},
{ fetchPolicy: 'network-only' },
)
})
}

const handleSearchClear = () => {
startTransition(() => {
reset()
refetch({
q: '',
unreadMessages: isInUnreadTab,
archived: isInArchivedTab,
})
refetch(
{
q: '',
unreadMessages: isInUnreadTab,
archived: isInArchivedTab,
},
{ fetchPolicy: 'network-only' },
)
})
}

const handleChange = (event: React.SyntheticEvent, newTab: string) => {
setTab(newTab as ChatTabValues)
startRefetchTransition(() => {
setRenderList(false)
refetch(
{
q: searchValue,
unreadMessages: newTab === CHAT_TAB_VALUES.unread,
archived: newTab === CHAT_TAB_VALUES.archived,
},
{ fetchPolicy: 'store-and-network' },
{ fetchPolicy: 'network-only' },
)
})
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider consistent renderList handling across all refetch scenarios.

While handleChange sets renderList to false before refetch, the search handlers don't. This could lead to inconsistent behavior when the Virtuoso component needs to be remounted.

Apply this diff to maintain consistency:

  const handleSearchChange: ChangeEventHandler<HTMLInputElement> = (e) => {
    const value = e.target.value || ''
    startTransition(() => {
+     setRenderList(false)
      refetch(
        {
          q: value,
          unreadMessages: isInUnreadTab,
          archived: isInArchivedTab,
        },
        { fetchPolicy: 'network-only' },
      )
    })
  }

  const handleSearchClear = () => {
    startTransition(() => {
      reset()
+     setRenderList(false)
      refetch(
        {
          q: '',
          unreadMessages: isInUnreadTab,
          archived: isInArchivedTab,
        },
        { fetchPolicy: 'network-only' },
      )
    })
  }
📝 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
const handleSearchChange: ChangeEventHandler<HTMLInputElement> = (e) => {
const value = e.target.value || ''
startTransition(() => {
refetch({
q: value,
unreadMessages: isInUnreadTab,
archived: isInArchivedTab,
})
refetch(
{
q: value,
unreadMessages: isInUnreadTab,
archived: isInArchivedTab,
},
{ fetchPolicy: 'network-only' },
)
})
}
const handleSearchClear = () => {
startTransition(() => {
reset()
refetch({
q: '',
unreadMessages: isInUnreadTab,
archived: isInArchivedTab,
})
refetch(
{
q: '',
unreadMessages: isInUnreadTab,
archived: isInArchivedTab,
},
{ fetchPolicy: 'network-only' },
)
})
}
const handleChange = (event: React.SyntheticEvent, newTab: string) => {
setTab(newTab as ChatTabValues)
startRefetchTransition(() => {
setRenderList(false)
refetch(
{
q: searchValue,
unreadMessages: newTab === CHAT_TAB_VALUES.unread,
archived: newTab === CHAT_TAB_VALUES.archived,
},
{ fetchPolicy: 'store-and-network' },
{ fetchPolicy: 'network-only' },
)
})
}
const handleSearchChange: ChangeEventHandler<HTMLInputElement> = (e) => {
const value = e.target.value || ''
startTransition(() => {
setRenderList(false)
refetch(
{
q: value,
unreadMessages: isInUnreadTab,
archived: isInArchivedTab,
},
{ fetchPolicy: 'network-only' },
)
})
}
const handleSearchClear = () => {
startTransition(() => {
reset()
setRenderList(false)
refetch(
{
q: '',
unreadMessages: isInUnreadTab,
archived: isInArchivedTab,
},
{ fetchPolicy: 'network-only' },
)
})
}
const handleChange = (event: React.SyntheticEvent, newTab: string) => {
setTab(newTab as ChatTabValues)
startRefetchTransition(() => {
setRenderList(false)
refetch(
{
q: searchValue,
unreadMessages: newTab === CHAT_TAB_VALUES.unread,
archived: newTab === CHAT_TAB_VALUES.archived,
},
{ fetchPolicy: 'network-only' },
)
})
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

4 participants