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: removed loader from inbox #420

Merged
merged 1 commit into from
Oct 28, 2024
Merged

fix: removed loader from inbox #420

merged 1 commit into from
Oct 28, 2024

Conversation

deewakar-k
Copy link
Contributor

@deewakar-k deewakar-k commented Oct 28, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced error handling during item management processes.
    • Improved item status updates for better visibility across different views.
  • Bug Fixes

    • Disabled loading message display when items are loading.
    • Commented out delete functionality to prevent unintended deletions.
  • Refactor

    • Updated logic for toggling item status in the inbox.
    • Standardized error handling across multiple fetching methods.

Copy link

coderabbitai bot commented Oct 28, 2024

Walkthrough

The changes in this pull request involve modifications to the InboxItems component and the cycle.store.ts file. In InboxItems, the loading state display and delete functionality have been commented out, while the item status toggling logic has been updated. In cycle.store.ts, error handling has been enhanced, and item management logic has been refactored to improve how items are updated and errors are handled during API calls.

Changes

File Path Change Summary
apps/frontend/src/components/Inbox/InboxItems.tsx Commented out loading state rendering and delete functionality; updated handleDone to toggle item status between "done" and "null".
apps/frontend/src/lib/store/cycle.store.ts Enhanced error handling with throw error statements in createItem and updateItem; refactored updateItem to include updateItemsInView for better item management.

Possibly related PRs

  • fix: today, inbox, this-week items blink on state change #364: The changes in this PR also modify the handleDone function in the InboxItems component, which is directly related to the updates made in the main PR regarding item status toggling.
  • feat: overdue items  #377: This PR introduces new methods for fetching items, including fetchToday and fetchOverdue, which are relevant to the overall item management context that the main PR is addressing, particularly in how items are handled in the store.

Suggested labels

ready to be merged

Suggested reviewers

  • sajdakabir
  • madhav-relish

Poem

In the inbox where items lay,
A toggle here, a comment play.
Errors caught, and states refined,
In the store, all well aligned.
Hopping forward, changes bright,
A rabbit’s cheer for code delight! 🐇✨


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

@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 and nitpick comments (3)
apps/frontend/src/components/Inbox/InboxItems.tsx (2)

Line range hint 128-134: Remove or properly disable the delete functionality.

Having a non-functional delete button in the menu can confuse users. Either:

  1. Remove the delete option entirely from the menu
  2. Disable it visually and add a tooltip explaining why
  3. Re-implement the delete functionality if it's still needed

If you're temporarily disabling delete, consider this implementation:

    {
      name: "Delete",
      icon: "weui:delete-outlined",
      color: "#C45205",
-     //     onClick: () => handleDelete(item._id!),
+     disabled: true,
+     tooltip: "Delete functionality temporarily unavailable"
    },

Line range hint 52-71: Improve status handling and error management.

The current implementation has several potential issues:

  1. Using "null" as a status is not semantically clear
  2. No error handling for failed optimistic updates
  3. Hardcoded animation duration

Consider this improved implementation:

  const handleDone = useCallback(
    (event: React.MouseEvent, id: string, currentStatus: string | undefined) => {
      event.stopPropagation()
      if (id) {
-       const newStatus = currentStatus === "done" ? "null" : "done"
+       const newStatus = currentStatus === "done" ? "pending" : "done"
        setAnimatingItems((prev) => new Set(prev).add(id))
        setOptimisticDoneItems((prev) => {
          const newSet = new Set(prev)
          if (newStatus === "done") {
            newSet.add(id)
          } else {
            newSet.delete(id)
          }
          return newSet
        })

+       const ANIMATION_DURATION = 400 // ms
        setTimeout(async () => {
-         updateItem(session, { status: newStatus }, id)
+         try {
+           await updateItem(session, { status: newStatus }, id)
+         } catch (error) {
+           // Revert optimistic update on failure
+           setOptimisticDoneItems((prev) => {
+             const newSet = new Set(prev)
+             if (currentStatus === "done") {
+               newSet.add(id)
+             } else {
+               newSet.delete(id)
+             }
+             return newSet
+           })
+           console.error("Failed to update item status:", error)
+         }
          setAnimatingItems((prev) => {
            const newSet = new Set(prev)
            newSet.delete(id)
            return newSet
          })
-       }, 400)
+       }, ANIMATION_DURATION)
      }
    },
    [updateItem, session]
  )
apps/frontend/src/lib/store/cycle.store.ts (1)

Line range hint 292-379: Consider improving the update mechanism.

The current implementation has several areas that could be enhanced:

  1. The updateItemsInView function is duplicated - once for optimistic updates and once for server response updates.
  2. There's a potential race condition where a slow server response could override more recent optimistic updates.
  3. Failed updates don't rollback the optimistic changes.

Consider refactoring like this:

interface UpdateState {
  previousState: ExtendedCycleItemStore;
  version: number;
}

// Store the previous state and version for potential rollback
const updateState = (updates: Partial<CycleItem>, id: string, version: number) => {
  set((state) => {
    // Store current state for potential rollback
    previousStates.set(version, state);

    const updateItemsInView = (items: CycleItem[], isOverdue = false) => {
      if (isOverdue && updates.status === "done") {
        return items.filter((item) => item._id !== id);
      }
      return items.map((item) =>
        item._id === id ? { ...item, ...updates } : item
      );
    };

    return {
      inbox: { ...state.inbox, items: updateItemsInView(state.inbox.items) },
      today: { ...state.today, items: updateItemsInView(state.today.items) },
      overdue: {
        ...state.overdue,
        items: updateItemsInView(state.overdue.items, true),
      },
      thisWeek: {
        ...state.thisWeek,
        items: updateItemsInView(state.thisWeek.items),
      },
      items: updateItemsInView(state.items),
      currentItem:
        state.currentItem?._id === id
          ? { ...state.currentItem, ...updates }
          : state.currentItem,
    };
  });
};

// Rollback to previous state if update fails
const rollback = (version: number) => {
  const previousState = previousStates.get(version);
  if (previousState) {
    set(previousState);
    previousStates.delete(version);
  }
};

This approach:

  1. Eliminates code duplication
  2. Provides rollback capability
  3. Tracks versions to handle race conditions
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4c368db and f0314d7.

📒 Files selected for processing (2)
  • apps/frontend/src/components/Inbox/InboxItems.tsx (1 hunks)
  • apps/frontend/src/lib/store/cycle.store.ts (1 hunks)
🔇 Additional comments (3)
apps/frontend/src/components/Inbox/InboxItems.tsx (1)

Line range hint 136-136: Verify the filtering logic with optimistic updates.

The current implementation filters out items with status "done", but the optimistic updates might cause inconsistencies in the UI. We should ensure that items are properly removed from view when marked as done.

Let's verify the component's behavior:

apps/frontend/src/lib/store/cycle.store.ts (2)

285-285: LGTM: Improved error handling.

The addition of throw error after setting the error state is a good practice. It allows both local state updates and error propagation to calling components for additional error handling if needed.


Line range hint 1-379: Verify alignment with PR objective.

The PR's objective is to "remove loader from inbox", but the changes include significant refactoring of error handling and item management logic. While these changes appear to be improvements, please clarify if they are intentional and related to the loader removal.

Let's check for any loader-related changes in the codebase:

Comment on lines +101 to +107
/* if (isLoading) {
return (
<div className="flex flex-col gap-4">
<p>loading...</p>
</div>
)
}
} */
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Consider implementing a better loading state pattern.

While removing the basic loading text improves the UI, we should still provide users with feedback during data fetching. Consider implementing a skeleton loader or a subtle loading indicator to maintain good UX.

Here's a suggested implementation using a skeleton loader:

+ import { Skeleton } from "@/components/ui/skeleton"
+
+ if (isLoading) {
+   return (
+     <div className="flex flex-col gap-4">
+       {[...Array(3)].map((_, i) => (
+         <div key={i} className="flex items-center space-x-4">
+           <Skeleton className="h-4 w-4 rounded-full" />
+           <div className="space-y-2">
+             <Skeleton className="h-4 w-[250px]" />
+             <Skeleton className="h-4 w-[200px]" />
+           </div>
+         </div>
+       ))}
+     </div>
+   )
+ }

Committable suggestion was skipped due to low confidence.

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.

2 participants