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: persisted state for toggle in notes #624

Merged
merged 1 commit into from
Nov 19, 2024
Merged

Conversation

deewakar-k
Copy link
Contributor

What did you ship?

Fixes:

  • #XXX (GitHub issue number)
  • MAR-XXX (Linear issue number - should be visible at the bottom of the GitHub issue description)

Checklist:

  • I have self-reviewed the code (A decent size PR without self-review might be rejected)
  • I pinky swear that my codes gonna work as I have testing every possible scenario.
  • I ignored Coderabbit suggestion because it does not make any sense.
  • I took Coderabbit suggestion under consideration as some of it makes sense.
  • I have commented my code, particularly in hard-to-understand areas.

OR:

  • shut up and let me cook.

Copy link

coderabbitai bot commented Nov 19, 2024

📝 Walkthrough

Walkthrough

The NotesPage component in NotesPage.tsx has been updated to improve state management and error handling. A new hook, usePersistedState, replaces useState for the closeToggle variable, allowing its state to persist across remounts. The logic for fetching notes is now encapsulated in the fetchTheNotes function, with enhanced error handling. Additional adjustments include refining the handling of non-existent notes, implementing a cleanup function for unsaved changes, and streamlining the note-saving logic.

Changes

File Path Change Summary
apps/frontend/src/components/Notes/NotesPage.tsx Introduced usePersistedState for closeToggle, improved note fetching and error handling, refined note management logic, and added cleanup for unsaved changes.

Possibly related PRs

Suggested labels

rtbm

Suggested reviewers

  • sajdakabir
  • oliursahin

Poem

In the land of notes, where ideas bloom,
A toggle now stays, dispelling the gloom.
Fetching with care, errors kept at bay,
Our notes dance freely, come what may!
With each little change, we hop and we cheer,
For a better NotesPage, the future is clear! 🐇✨


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: 0

🧹 Outside diff range and nitpick comments (3)
apps/frontend/src/components/Notes/NotesPage.tsx (3)

Line range hint 50-57: Consider enhancing error handling with user feedback.

While the error handling is functional, consider adding user feedback for a better UX:

 const fetchTheNotes = useCallback(async (): Promise<void> => {
   try {
     await fetchNotes(session)
     setIsFetched(true)
   } catch (error) {
     setIsFetched(false)
+    console.error('Failed to fetch notes:', error)
+    // Consider adding a toast notification or error state
+    // to inform users when notes fail to load
   }
 }, [session, fetchNotes, setIsFetched])

Line range hint 171-191: Critical: Improve error handling in note deletion.

The current implementation has potential issues:

  1. Race condition: UI updates might proceed even if deletion fails
  2. No user feedback on error
  3. Possible inconsistent state if error occurs during navigation
 const handleDeleteNote = async (n: Note): Promise<void> => {
   if (!session || !n) return
 
   try {
     await deleteNote(session, n)
     const remainingNotes = notes.filter((n_) => n_._id !== n._id)
 
     if (n._id === note?._id) {
       if (remainingNotes.length <= 0) {
         const newNote = await addNewNote()
         // No need to redirect here since addNewNote already does the routing
       } else {
         router.push(`/space/notes/${remainingNotes[0]._id}`)
       }
     }
   } catch (error) {
-    console.error("Error deleting note:", error)
+    console.error("Failed to delete note:", error)
+    // Prevent UI updates on error
+    return
+    // Consider adding error feedback:
+    // showErrorToast('Failed to delete note. Please try again.')
   }
 }

Line range hint 193-205: Consider improving save handling and cleanup.

The current implementation has several areas for improvement:

  1. Race conditions between auto and manual saves
  2. No error handling for failed saves
  3. Potential memory leaks
 useEffect(() => {
   if (note && isSaved) {
-    saveNoteToServer({ ...note, title, description: content })
+    const save = async () => {
+      try {
+        await saveNoteToServer({ ...note, title, description: content })
+      } catch (error) {
+        console.error('Failed to save note:', error)
+        setIsSaved(false)
+        // Consider adding error feedback
+      }
+    }
+    save()
   }
 }, [note, saveNoteToServer, isSaved])

 useEffect(() => {
   const handleBeforeUnload = (e: BeforeUnloadEvent) => {
     if (!isSaved) {
       e.preventDefault()
+      // Consider showing a custom message
+      e.returnValue = 'You have unsaved changes. Are you sure you want to leave?'
     }
   }

   window.addEventListener("beforeunload", handleBeforeUnload)

   return () => {
     window.removeEventListener("beforeunload", handleBeforeUnload)
+    // Clear any pending timeouts
+    if (timeoutId.current) {
+      clearTimeout(timeoutId.current)
+    }
   }
-}, [isSaved])
+}, [isSaved, timeoutId])

Also applies to: 124-139

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e279f08 and 384b10c.

📒 Files selected for processing (1)
  • apps/frontend/src/components/Notes/NotesPage.tsx (2 hunks)
🔇 Additional comments (2)
apps/frontend/src/components/Notes/NotesPage.tsx (2)

13-13: LGTM: Good use of persisted state for toggle.

The introduction of usePersistedState hook and its implementation for closeToggle effectively addresses the PR objective of persisting the toggle state across sessions.

Also applies to: 46-46


46-46: Verify the persistence of toggle state.

The implementation successfully addresses the PR objective by using usePersistedState. To ensure it works as expected:

Also applies to: 46-46

✅ Verification successful

Implementation of toggle state persistence is correctly implemented and consistent

The verification shows that:

  • The usePersistedState hook is properly implemented and imported from the correct location
  • It's being used consistently across components (TodayPage and NotesPage)
  • The hook implementation follows React's useState pattern with proper persistence logic
  • The toggle state implementation in NotesPage follows the same pattern as other persisted states in the codebase
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other instances of toggle state persistence
# and verify the implementation pattern

# Look for other usePersistedState usage
rg "usePersistedState" --type typescript

# Check for similar toggle state implementations
ast-grep --pattern 'const [$_1, $_2] = use$_3State("$_4Toggle", $_5)'

Length of output: 147


Script:

#!/bin/bash
# Description: Check for other instances of toggle state persistence
# and verify the implementation pattern with correct file type

# Look for usePersistedState usage
rg "usePersistedState" -t ts -t tsx

# Check for the hook implementation
fd -e ts -e tsx --exec cat {} \; | grep -A 5 "usePersistedState"

# Look for similar toggle state patterns
rg "Toggle.*useState|useState.*Toggle" -t ts -t tsx

Length of output: 1456

@sajdakabir sajdakabir merged commit 495c50a into preview Nov 19, 2024
6 checks passed
@sajdakabir sajdakabir deleted the fix/notes-stack branch November 19, 2024 08:44
This was referenced Nov 28, 2024
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