Skip to content

Conversation

kushagrasarathe
Copy link
Contributor

@kushagrasarathe kushagrasarathe commented Apr 10, 2025

contributes to TASK-10053

Summary by CodeRabbit

  • New Features

    • Introduced enhanced loading indicators throughout the app to provide clearer feedback during data retrieval, setup, and authentication processes.
    • Added a new token validation mechanism to ensure more reliable user access.
  • Refactor

    • Streamlined data fetching and state management across various pages, resulting in smoother transitions, refined error handling, and improved performance.
    • Updated caching strategies for user and wallet data to maintain consistency during asynchronous updates.
    • Improved loading state management in components for better user experience.

Copy link

vercel bot commented Apr 10, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
peanut-ui ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 10, 2025 4:41pm

Copy link
Contributor

coderabbitai bot commented Apr 10, 2025

Walkthrough

This pull request refactors multiple mobile UI pages to streamline data fetching and loading state management. It replaces local state handling with React Query hooks, consolidates loading flags across components, and introduces a utility to validate JWT tokens. Additionally, import statements are reorganized for clarity and query configurations are enhanced, ensuring a more efficient and robust handling of asynchronous data across the application.

Changes

File(s) Change Summary
src/app/(mobile-ui)/history/page.tsx, src/app/(mobile-ui)/home/page.tsx, src/app/(mobile-ui)/layout.tsx, src/app/(setup)/setup/page.tsx Refactored data fetching and loading state management by replacing local state and useEffect logic with React Query hooks; combined multiple loading flags; added token validation via hasValidJwtToken; updated pagination and conditional rendering.
src/components/Home/HomeWaitlist.tsx, src/components/Setup/components/SetupWrapper.tsx Replaced a custom loading animation with the PeanutLoading component and reorganized import statements for improved clarity.
src/hooks/query/user.ts, src/hooks/wallet/useWallet.ts Updated React Query configurations by adding placeholderData (using keepPreviousData), increasing stale and garbage collection times, and refining state management logic in hooks.
src/utils/auth.ts Introduced a new function hasValidJwtToken to verify the presence and validity of JWT tokens from cookies.
src/components/Global/PeanutLoading/index.tsx Modified PeanutLoading component to accept an optional coverFullScreen prop for enhanced styling.

Sequence Diagram(s)

sequenceDiagram
    participant HP as HistoryPage
    participant RQ as useQuery Hook
    participant QF as Query Function
    HP ->> RQ: Call useQuery with queryKey & queryFn
    RQ ->> QF: Execute dashboard data fetch
    QF -->> RQ: Return dashboard data
    RQ -->> HP: Provide data, loading, and error states
Loading
sequenceDiagram
    participant L as Layout Component
    participant UA as useAuth Hook
    participant Auth as Auth Utils (hasValidJwtToken)
    participant UI as UI Renderer
    L ->> UA: Retrieve username, isFetchingUser, user
    L ->> Auth: Validate JWT token
    Auth -->> L: Return token validity
    alt Data not ready or invalid token
        L ->> UI: Render PeanutLoading component
    else Data ready and valid token
        L ->> UI: Render page content
    end
Loading

Possibly related PRs

Suggested reviewers

  • jjramirezn

Poem

I hopped through lines of code at dawn,
Refactored logic, now crisp and strong.
With queries swift and tokens clear,
My bunny heart brings joyful cheer.
Codes and carrots, dancing in delight—
A rabbit's verse shining through the night!


📜 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 181622d and df7f944.

📒 Files selected for processing (4)
  • src/app/(mobile-ui)/home/page.tsx (3 hunks)
  • src/app/(mobile-ui)/layout.tsx (3 hunks)
  • src/components/Global/PeanutLoading/index.tsx (1 hunks)
  • src/components/Home/HomeWaitlist.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/components/Home/HomeWaitlist.tsx
  • src/app/(mobile-ui)/layout.tsx
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/app/(mobile-ui)/home/page.tsx (2)
src/context/authContext.tsx (1)
  • useAuth (317-323)
src/components/Global/PeanutLoading/index.tsx (1)
  • PeanutLoading (4-18)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Deploy-Preview
🔇 Additional comments (9)
src/app/(mobile-ui)/home/page.tsx (5)

41-43: Good addition of content readiness tracking.

This state variable provides a more controlled approach to showing loading states, helping to prevent UI flashes during transitions.


44-44: Improved authorization state handling.

Including isFetchingUser from the auth hook allows for better coordination between different loading states in the component.


162-162: Well-structured combined loading state.

This logical condition effectively combines multiple loading states into a single variable, making the code more maintainable and reducing duplication in conditional rendering.


164-176: Good implementation of delayed content rendering.

The useEffect hook with a small timeout creates a smoother transition between loading and content states. The cleanup function properly handles the timeout to prevent memory leaks.


178-181: Improved loading state handling.

The enhanced conditional rendering now accounts for both data fetching states and content readiness, providing a better user experience with the full-screen loading component.

src/components/Global/PeanutLoading/index.tsx (4)

2-2: Good addition of tailwind-merge utility.

Using twMerge is the correct approach for conditionally combining Tailwind classes, preventing class conflicts and duplication.


4-4: Well-structured component API enhancement.

The addition of the coverFullScreen prop with a default value makes the component more versatile while maintaining backward compatibility.


6-11: Effective conditional styling implementation.

The use of twMerge with conditional class application is clean and maintains good readability. The full-screen mode adds appropriate positioning and z-index for overlay functionality.


12-12: Consistent use of twMerge.

Using twMerge for the inner div maintains consistency with the outer div styling approach, making future class additions more maintainable.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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

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

🧹 Nitpick comments (3)
src/app/(setup)/setup/page.tsx (1)

99-99: Remove outdated TODO comment

The TODO comment about adding loading state is now redundant since you've already implemented it.

-    // todo: add loading state
src/app/(mobile-ui)/layout.tsx (1)

45-50: Better loading state presentation.

The loading state now considers both component readiness and user fetching status, displaying a centered loading indicator for a smoother user experience. This aligns perfectly with the PR's goal of improving loading states.

Consider adding a timeout for the loading state to prevent an indefinite loading screen in case of network issues:

 useEffect(() => {
     // check for JWT token
     setHasToken(hasValidJwtToken())

     setIsReady(true)
+    
+    // Add a timeout to prevent indefinite loading
+    const timer = setTimeout(() => {
+        setIsReady(true);
+    }, 5000); // 5 seconds timeout
+    
+    return () => clearTimeout(timer);
 }, [])
src/app/(mobile-ui)/history/page.tsx (1)

36-99: Consider adding error handling for the dashboard query.

While the history query has proper error handling, the dashboard query doesn't explicitly handle errors. Consider adding error handling for the dashboard query to provide a better user experience when dashboard data fails to load.

 const { data: dashboardData, isLoading: isLoadingDashboard } = useQuery({
     queryKey: ['dashboardData', address],
     queryFn: () => composeLinkDataArray(address ?? ''),
     enabled: !!address,
     staleTime: 5 * 60 * 1000, // 5 minutes
     gcTime: 10 * 60 * 1000, // 10 minutes
     placeholderData: keepPreviousData,
+    onError: (error) => {
+        console.error('Failed to fetch dashboard data:', error);
+        Sentry.captureException(error);
+    },
 })
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 60f5695 and 181622d.

📒 Files selected for processing (9)
  • src/app/(mobile-ui)/history/page.tsx (4 hunks)
  • src/app/(mobile-ui)/home/page.tsx (2 hunks)
  • src/app/(mobile-ui)/layout.tsx (3 hunks)
  • src/app/(setup)/setup/page.tsx (4 hunks)
  • src/components/Home/HomeWaitlist.tsx (2 hunks)
  • src/components/Setup/components/SetupWrapper.tsx (1 hunks)
  • src/hooks/query/user.ts (2 hunks)
  • src/hooks/wallet/useWallet.ts (2 hunks)
  • src/utils/auth.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (5)
src/app/(setup)/setup/page.tsx (1)
src/components/Global/PeanutLoading/index.tsx (1)
  • PeanutLoading (3-12)
src/components/Home/HomeWaitlist.tsx (1)
src/components/Global/PeanutLoading/index.tsx (1)
  • PeanutLoading (3-12)
src/app/(mobile-ui)/home/page.tsx (1)
src/context/authContext.tsx (1)
  • useAuth (317-323)
src/app/(mobile-ui)/layout.tsx (3)
src/context/authContext.tsx (1)
  • useAuth (317-323)
src/utils/auth.ts (1)
  • hasValidJwtToken (5-36)
src/components/Global/PeanutLoading/index.tsx (1)
  • PeanutLoading (3-12)
src/hooks/wallet/useWallet.ts (1)
src/redux/slices/wallet-slice.ts (1)
  • walletActions (89-89)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Deploy-Preview
🔇 Additional comments (27)
src/hooks/query/user.ts (2)

7-7: Good addition of keepPreviousData import

This is a valuable addition to support the enhanced data loading behavior.


48-49: Excellent enhancement of loading state management

Adding placeholderData: keepPreviousData ensures that previous successful query data is retained while new data is being fetched. This improves the user experience by maintaining UI continuity during refetches, preventing empty or loading states from flashing to users.

src/app/(setup)/setup/page.tsx (4)

3-9: Good job organizing imports

The addition of the PeanutLoading component and restructuring of imports improves code organization.


21-21: Proper initialization of loading state

Good addition of the loading state variable initialized to true to ensure the loading spinner appears immediately on page load.


25-47: Well-implemented loading state management in async function

The changes properly manage the loading state during passkey support checking:

  1. Setting loading to true at the beginning of the function
  2. Using a finally block to ensure loading state is reset regardless of success or failure

This is excellent error handling practice.


92-97: Clear conditional rendering of loading component

Good implementation of the loading state UI that provides visual feedback to users during the passkey support check.

src/app/(mobile-ui)/home/page.tsx (2)

41-41: Good extraction of the isFetchingUser from auth context

Adding isFetchingUser to the destructured values from useAuth() allows for more comprehensive loading state management.


159-161: Excellent consolidation of loading states

Creating a unified isLoading variable that considers both user and wallet fetching states ensures that the loading spinner is displayed until all necessary data is fully loaded. This prevents showing incomplete or inconsistent UI to users.

src/components/Home/HomeWaitlist.tsx (2)

8-8: Good addition of PeanutLoading import

Adding the standard loading component improves consistency across the application.


20-22: Great replacement of custom loading UI with standardized component

Replacing the custom loading JSX with the reusable PeanutLoading component promotes UI consistency throughout the application and simplifies the code.

src/components/Setup/components/SetupWrapper.tsx (2)

5-6: Import organization improvement looks good.

The imports for BeforeInstallPromptEvent, LayoutType, ScreenId, and InstallPWA have been properly organized into their respective paths, making the code more maintainable.


9-9: Consistent React import organization.

The reordering of React imports with Children first follows a logical pattern since it's used more prominently in the component.

src/hooks/wallet/useWallet.ts (4)

27-27: Addition of keepPreviousData improves UX during loading states.

Adding this import from React Query allows previous data to be shown while new data is being fetched, preventing UI flicker.


237-239: Improved query configuration enhances data persistence.

The changes to the query configuration improve user experience by:

  1. Increasing stale time from 30s to 60s reduces unnecessary refetches
  2. Increasing cache time from 1m to 5m prevents data loss during short navigation
  3. Using keepPreviousData maintains UI state while loading fresh data

These optimizations align well with the PR objective to improve loading states.


243-247: Refined loading state management logic.

The updated condition now only sets isFetchingWallets to true when there are no wallets yet, avoiding unnecessary state updates when subsequent queries are loading but wallets data already exists.


248-248: Proper dependency update in useEffect.

Adding wallets.length to the dependency array ensures the effect runs correctly when the wallet count changes, preventing stale loading states.

src/utils/auth.ts (1)

1-36: Well-implemented JWT token validation utility.

This new utility function is well-structured and thoroughly handles various edge cases:

  • Checks for browser environment
  • Validates token structure
  • Correctly decodes the JWT payload
  • Properly handles expiration validation
  • Includes robust error handling

The implementation follows security best practices for client-side token validation.

src/app/(mobile-ui)/layout.tsx (3)

5-5: Good additions for loading state management.

Importing PeanutLoading and hasValidJwtToken enables better handling of application loading states, supporting the PR's objective to fix loading states.

Also applies to: 12-12


23-25: Enhanced auth state tracking.

The updated destructuring from useAuth() provides more comprehensive access to user state data, and the new hasToken state effectively tracks JWT validity.


38-43: Improved initialization logic with token validation.

The updated effect now properly checks for a valid JWT token before considering the layout ready, which helps prevent invalid authentication states.

src/app/(mobile-ui)/history/page.tsx (7)

15-15: Well-organized import modifications.

The imports have been properly updated to support the React Query integration. Adding formatPaymentStatus to the imported utilities and bringing in the necessary React Query hooks (keepPreviousData, useInfiniteQuery, useQuery) while streamlining the React imports to only what's needed improves code organization.

Also applies to: 23-23, 26-26


36-43: Good implementation of React Query for dashboard data.

Replacing local state management with React Query is a solid improvement. The configuration is well thought out with:

  • Proper query keys that depend on the user's address
  • Appropriate staleTime and gcTime for efficient caching
  • Use of keepPreviousData to prevent UI flashing during refetches
  • Conditional execution based on address availability

This implementation follows React Query best practices and will improve data fetching reliability.


46-47: Early return pattern properly implemented.

Adding this null check for dashboardData is a good defensive programming practice, preventing potential errors when data isn't available yet.


86-86: Robust nextPage calculation.

The updated logic for determining the next page now safely handles the case where dashboardData might be undefined by using the nullish coalescing operator. This is a good improvement for error prevention.


91-99: Properly configured useInfiniteQuery.

The infinite query implementation has been improved with:

  • Updated query key that properly depends on dashboardData
  • More robust enabled condition
  • Appropriate cache configuration with staleTime and gcTime
  • Use of keepPreviousData for a better UX during data refetching

These changes will ensure more reliable query behavior and prevent unnecessary loading states.


121-121: Improved loading state condition.

This condition now properly checks both loading states and ensures we only show the loading indicator when there's truly no data available to display. This prevents loading flashes when data is already available but being refreshed.


131-131: Simplified empty state logic.

The condition for showing the empty state has been simplified and made more direct. This makes the code more readable and maintainable.

@jjramirezn jjramirezn merged commit fc65929 into peanut-wallet-dev Apr 10, 2025
5 checks passed
@Hugo0 Hugo0 deleted the fix/loading-states branch July 3, 2025 18:24
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