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

Refetch transactions and metadatas at an interval after the last refetch #245

Merged
merged 8 commits into from
Feb 6, 2025

Conversation

hansl
Copy link
Contributor

@hansl hansl commented Feb 6, 2025

Fixes #239

This is lacking tests as I'm not sure how to test refetch without having to wait 3 seconds between mocks.

I tested it (and false tested too) manually and it works wonderfully.

Summary by CodeRabbit

  • New Features

    • Implemented an auto-refresh mechanism that updates the transaction history and related metadata periodically, ensuring the display remains current.
  • Refactor

    • Updated method signatures to support asynchronous operations, enhancing the handling of data fetching in the components.

@hansl hansl requested a review from fmorency February 6, 2025 00:11
Copy link
Contributor

coderabbitai bot commented Feb 6, 2025

Warning

Rate limit exceeded

@hansl has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 22 minutes and 57 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 0a1ee7f and 44bd785.

📒 Files selected for processing (3)
  • components/bank/components/historyBox.tsx (2 hunks)
  • components/groups/components/groupControls.tsx (1 hunks)
  • hooks/useDebounceEffect.ts (1 hunks)

Walkthrough

This change introduces an interval-based refresh mechanism to the HistoryBox component. A useEffect hook is implemented to manage the periodic fetching of transaction data and metadata every 1000 milliseconds. The refetch function's signature is updated to return a Promise<any>, allowing for asynchronous handling. The changes also ensure that multiple queries do not run simultaneously by awaiting the completion of previous fetches before initiating new ones.

Changes

File Group Change Summary
components/bank/.../historyBox.tsx Introduced a useEffect to set a timer for refetching transaction data and metadata every 1000ms. Updated refetch to return a Promise<any> and modified cleanup logic.
components/groups/.../groupControls.tsx Changed refetchHistory property in GroupControlsProps from returning void to returning a Promise<any>, indicating asynchronous behavior.

Assessment against linked issues

Objective Addressed Explanation
Auto-refresh transaction history every X seconds (#239)

Possibly related PRs

  • feat: better history #98: Changes in the HistoryBox component's refetch function signature to return a Promise<any> are directly related to the modifications in GroupControlsProps.
  • test: improve history box #107: Updates in the HistoryBox component's refetch function are related to the asynchronous behavior changes in GroupControlsProps.

Suggested reviewers

  • chalabi2
  • jgryffindor

Poem

I'm just a rabbit hopping through code,
With a timer set, my data's bestowed.
Every second, I fetch with delight,
Keeping history fresh, oh what a sight!
In this digital burrow, we work and play,
Celebrating updates, hip-hip-hooray!
🥕🐇


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

codecov bot commented Feb 6, 2025

Codecov Report

Attention: Patch coverage is 70.58824% with 10 lines in your changes missing coverage. Please review.

Project coverage is 55.10%. Comparing base (8af1d4e) to head (44bd785).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
hooks/useDebounceEffect.ts 60.00% 10 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #245      +/-   ##
==========================================
+ Coverage   55.08%   55.10%   +0.02%     
==========================================
  Files         200      201       +1     
  Lines       16873    16905      +32     
==========================================
+ Hits         9294     9316      +22     
- Misses       7579     7589      +10     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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

🧹 Nitpick comments (1)
components/bank/components/historyBox.tsx (1)

9-9: Use standard comment syntax.

The comment on line 9 uses triple slashes ///, which are typically reserved for TypeScript directives. Consider using double slashes // for regular comments to improve readability and prevent any unintended compiler interpretations.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8af1d4e and bfc5155.

📒 Files selected for processing (1)
  • components/bank/components/historyBox.tsx (2 hunks)

components/bank/components/historyBox.tsx Outdated Show resolved Hide resolved
components/bank/components/historyBox.tsx Outdated Show resolved Hide resolved
@hansl hansl changed the title Refetch transactions and metadatas every 3 seconds after the last refetch Refetch transactions and metadatas at an interval after the last refetch Feb 6, 2025
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: 2

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bfc5155 and 9caa42f.

📒 Files selected for processing (2)
  • components/bank/components/historyBox.tsx (2 hunks)
  • components/groups/components/groupControls.tsx (1 hunks)
🔇 Additional comments (4)
components/bank/components/historyBox.tsx (4)

1-1: LGTM!

The imports are necessary for implementing the interval-based refresh mechanism.


43-43: Ensure refetch consistently returns a Promise<void>.

To maintain the integrity of the Promise chain in refetchInner, it's important that refetch always returns a Promise<void>. Using any type is not a good practice as it bypasses TypeScript's type checking.

Apply this diff to update the refetch type signature:

-refetch: () => Promise<any>;
+refetch: () => Promise<void>;

49-49: LGTM!

The destructuring of refetchMetadatas is necessary for implementing the metadata refresh functionality.


53-76: Refactor useEffect for reliable interval management and correct dependencies.

The current useEffect implementation uses a recursive setTimeout with manual Promise chaining and a done flag, which can be error-prone and complex. Additionally, the dependency array [refetchMetadatas] may lead to unintended re-executions of the effect, especially if metadatas changes frequently.

Recommendations:

  • Simplify interval management by using setInterval: This reduces complexity and ensures that the refetch functions are called at consistent intervals.
  • Adjust the dependency array: Include refetch and refetchMetadatas to ensure that the effect responds correctly if these functions change. If these functions are stable (do not change between renders), you can provide an empty dependency array [].
  • Ensure refetch and refetchMetadatas are stable: If they are recreated on every render, consider wrapping them with useCallback to prevent unnecessary effect re-runs.

Apply this refactored code:

 useEffect(() => {
-   let latestRefetch = Promise.resolve();
-   let done = false;
-   let timer = setTimeout(refetchInner, HISTORY_BOX_REFRESH_INTERVAL);

-   function refetchInner() {
-     if (done) return;

-     latestRefetch = latestRefetch
-       .then(() => refetch())
-       .then(() => refetchMetadatas())
-       .then(() => {
-         timer = setTimeout(refetchInner, HISTORY_BOX_REFRESH_INTERVAL);
-       });
-   }

-   return () => {
-     done = true;
-     clearTimeout(timer);
-   };
- }, [refetchMetadatas]);

+   useEffect(() => {
+     const intervalId = setInterval(() => {
+       refetch();
+       refetchMetadatas();
+     }, HISTORY_BOX_REFRESH_INTERVAL);
+
+     return () => {
+       clearInterval(intervalId);
+     };
+   }, [refetch, refetchMetadatas]);

This refactor:

  • Uses setInterval for consistent periodic execution.
  • Ensures proper cleanup with clearInterval to prevent memory leaks.
  • Updates the dependency array to include only refetch and refetchMetadatas for correct effect re-initialization.

components/bank/components/historyBox.tsx Outdated Show resolved Hide resolved
@@ -42,7 +42,7 @@ type GroupControlsProps = {
denomLoading: boolean;
isDenomError: boolean;
refetchBalances: () => void;
refetchHistory: () => void;
refetchHistory: () => Promise<any>;
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

Use Promise<void> instead of Promise<any>.

Using any type bypasses TypeScript's type checking. Since refetchHistory is used to trigger a refresh without returning any meaningful value, it should return Promise<void>.

Apply this diff to update the type signature:

-refetchHistory: () => Promise<any>;
+refetchHistory: () => Promise<void>;
📝 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
refetchHistory: () => Promise<any>;
refetchHistory: () => Promise<void>;

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

🧹 Nitpick comments (2)
components/bank/components/historyBox.tsx (2)

43-43: Consider using a more specific return type for refetch.

Using Promise<any> reduces type safety. Consider using a more specific return type that matches the actual return value of the refetch operation.

-  refetch: () => Promise<any>;
+  refetch: () => Promise<void>;

61-68: Add tests for the refetch functionality.

The refetch logic is currently not covered by tests. We can help implement tests using Jest's timer mocks to avoid actual delays.

Would you like me to generate test cases that demonstrate how to test the refetch functionality without introducing actual delays? The tests would use jest.useFakeTimers() and jest.advanceTimersByTime() to simulate the interval without waiting.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 61-68: components/bank/components/historyBox.tsx#L61-L68
Added lines #L61 - L68 were not covered by tests

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9caa42f and 0a1ee7f.

📒 Files selected for processing (1)
  • components/bank/components/historyBox.tsx (2 hunks)
🧰 Additional context used
📓 Learnings (1)
components/bank/components/historyBox.tsx (1)
Learnt from: hansl
PR: liftedinit/manifest-app#245
File: components/bank/components/historyBox.tsx:0-0
Timestamp: 2025-02-06T01:36:10.277Z
Learning: In the HistoryBox component, requests need to be debounced to prevent concurrent executions, ensuring that a new request starts only after the previous one completes.
🪛 GitHub Check: codecov/patch
components/bank/components/historyBox.tsx

[warning] 61-68: components/bank/components/historyBox.tsx#L61-L68
Added lines #L61 - L68 were not covered by tests

🔇 Additional comments (2)
components/bank/components/historyBox.tsx (2)

9-11: Adjust the refresh interval to match the PR objective.

The PR objective mentions a 3-second wait time, but the code uses 1 second (1000 milliseconds).

-const HISTORY_BOX_REFRESH_INTERVAL = 1000;
+const HISTORY_BOX_REFRESH_INTERVAL = 3000;

49-49: LGTM!

The hook usage is correct and follows React hooks best practices.

components/bank/components/historyBox.tsx Outdated Show resolved Hide resolved
Copy link
Contributor

@fmorency fmorency left a comment

Choose a reason for hiding this comment

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

ACK

@fmorency fmorency merged commit 6b6cef6 into liftedinit:main Feb 6, 2025
4 checks passed
@hansl hansl deleted the fix-239 branch February 6, 2025 16:14
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.

Refresh transaction history every X seconds
2 participants