Skip to content

fix: fix useApi interaction with useApiWithChain2 #1556

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

Merged
merged 5 commits into from
Sep 23, 2024

Conversation

AMIRKHANEF
Copy link
Member

@AMIRKHANEF AMIRKHANEF commented Sep 23, 2024

Works Done

  1. remove useless useEffect in useApi.ts
  2. add support for _endpoint and _genesisHash by fix interaction useApi with useApiWithChain2

Close: #1555

Summary by CodeRabbit

  • New Features

    • Introduced enhanced API connection management with two new functions for adding and handling API requests.
  • Bug Fixes

    • Streamlined logic for checking existing API connections to improve reliability.

Copy link
Contributor

coderabbitai bot commented Sep 23, 2024

Walkthrough

The changes introduce two new functions, addApiRequest and handleApiWithChain, to enhance the management of API requests within the useApi hook. Modifications to the useEffect hook ensure that API connections are handled more efficiently by checking the availability of _endpoint and _genesisHash. The overall structure of the code is improved for better clarity and maintainability.

Changes

File Change Summary
packages/extension-polkagate/src/hooks/useApi.ts Added methods: addApiRequest(endpointToRequest: string, genesisHash: string) and handleApiWithChain(manualEndpoint: string, genesisHash: string). Modified useEffect to utilize these new functions and updated dependencies.

Assessment against linked issues

Objective Addressed Explanation
useApi does not react to _endpoint and _genesisHash (#1555)

🐰 In the code where requests dwell,
New functions rise, all is well.
With endpoints checked and hashes clear,
Our API dances, full of cheer!
So hop along, let’s connect,
A brighter path we now reflect! 🌟


Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between ad9cafc and 158daf0.

Files selected for processing (1)
  • packages/extension-polkagate/src/hooks/useApi.ts (5 hunks)
Files skipped from review as they are similar to previous changes (1)
  • packages/extension-polkagate/src/hooks/useApi.ts

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

Commits

Files that changed from the base of the PR and between 6cd91ff and 2f26702.

Files selected for processing (1)
  • packages/extension-polkagate/src/hooks/useApi.ts (2 hunks)
Additional context used
Biome
packages/extension-polkagate/src/hooks/useApi.ts

[error] 207-207: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

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

Outside diff range and nitpick comments (2)
packages/extension-polkagate/src/hooks/useApi.ts (2)

106-107: Consider removing the commented-out console.log statement

Commented-out code can clutter the codebase and make it harder to maintain. If this log statement is no longer needed, it's best to remove it entirely. If it's kept for debugging purposes, consider using a logging library that allows for different log levels, so debug logs can be easily toggled on/off.


249-252: Consider removing the commented-out console.log statement

Similar to the previous comment, it's generally best to remove commented-out code to keep the codebase clean. If this log statement is needed for debugging, consider using a logging library with configurable log levels.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2f26702 and a0c7abd.

Files selected for processing (1)
  • packages/extension-polkagate/src/hooks/useApi.ts (5 hunks)
Additional comments not posted (2)
packages/extension-polkagate/src/hooks/useApi.ts (2)

198-217: Well-implemented handleManualApiRequest function

The handleManualApiRequest function is well-structured and follows good practices:

  1. It checks for existing API connections before initiating a new one, avoiding unnecessary reconnections.
  2. The use of optional chaining (savedApi?.api?.isConnected) is a good practice for safe property access.
  3. The function handles different scenarios (already requested, connected, new connection) appropriately.

Good job on this implementation!


221-226: Good addition of manual API request handling in useEffect

The addition of checks for _endpoint and _genesisHash at the beginning of the useEffect hook is a good improvement. It allows for more flexible API connection management, especially when integrating with useApiWithChain2. The early return when these conditions are met helps to avoid unnecessary processing.

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

Outside diff range and nitpick comments (2)
packages/extension-polkagate/src/hooks/useApi.ts (2)

106-107: Consider removing the commented-out console.log statement

Commented-out code can clutter the codebase and make it harder to maintain. If this log statement is no longer needed, it's best to remove it entirely. If it's kept for debugging purposes, consider using a logging library that allows for different log levels, so debug logs can be easily toggled on/off.


249-252: Remove commented-out console.log statement

Commented-out code can clutter the codebase and make it harder to maintain. If this log statement is no longer needed, it's best to remove it entirely. If it's kept for debugging purposes, consider using a logging library that allows for different log levels, so debug logs can be easily toggled on/off.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a0c7abd and 62f9fa3.

Files selected for processing (1)
  • packages/extension-polkagate/src/hooks/useApi.ts (5 hunks)
Additional comments not posted (2)
packages/extension-polkagate/src/hooks/useApi.ts (2)

Line range hint 127-134: Avoid direct state mutation in handleNewApi function

The current implementation directly mutates the apisContext.apis object, which can lead to unexpected behavior in React applications. It's recommended to create new objects to maintain immutability.

Apply this diff to avoid direct state mutation:

-    apisContext.apis[genesisHash] = toSaveApi;
-    apisContext.setIt({ ...apisContext.apis });
+    apisContext.setIt((prevApis) => ({
+      ...prevApis,
+      [genesisHash]: toSaveApi
+    }));

This approach updates the state immutably using the setter function of apisContext.setIt.


189-196: Avoid direct state mutation in addApiRequest function

The current implementation directly mutates the apisContext.apis object. To maintain immutability and prevent unexpected behavior, consider using an immutable update pattern.

Apply this diff to avoid direct state mutation:

  const addApiRequest = useCallback((endpointToRequest: string, genesisHash: string) => {
-   const toSaveApi = apisContext.apis[genesisHash] ?? [];
+   const toSaveApi = [...(apisContext.apis[genesisHash] ?? [])];

    toSaveApi.push({ endpoint: endpointToRequest, isRequested: true });

-   apisContext.apis[genesisHash] = toSaveApi;
-   apisContext.setIt({ ...apisContext.apis });
+   apisContext.setIt((prevApis) => ({
+     ...prevApis,
+     [genesisHash]: toSaveApi
+   }));
  }, [apisContext]);

This approach creates a new array for toSaveApi and uses the setter function of apisContext.setIt to update the state immutably.

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

Outside diff range and nitpick comments (2)
packages/extension-polkagate/src/hooks/useApi.ts (2)

106-106: Consider using a logging library for better debugging control

While commenting out console.log statements is good for production, it might hinder debugging. Consider using a logging library or environment-based logging to maintain debugging capabilities without affecting production code.

You could implement a simple logging utility:

const log = (message: string, ...args: any[]) => {
  if (process.env.NODE_ENV !== 'production') {
    console.log(message, ...args);
  }
};

// Usage
log('Successfully connected to existing API for genesis hash:', genesisHash);

249-251: Consider using a logging library for better debugging control

While commenting out console.log statements is good for production, it might hinder debugging. Consider using a logging library or environment-based logging to maintain debugging capabilities without affecting production code.

You could implement a simple logging utility as suggested in a previous comment.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 62f9fa3 and ad9cafc.

Files selected for processing (1)
  • packages/extension-polkagate/src/hooks/useApi.ts (5 hunks)
Additional comments not posted (2)
packages/extension-polkagate/src/hooks/useApi.ts (2)

Line range hint 127-134: LGTM: Proper handling of new API entry

The logic for adding a new API entry to toSaveApi is correct. Setting isRequested to false is appropriate as the API is now connected.


219-224: LGTM: New useEffect hook for handling _endpoint and _genesisHash

The new useEffect hook correctly handles the case when _endpoint and _genesisHash are available, which is crucial for the interaction with useApiWithChain2.

@Nick-1979 Nick-1979 merged commit 23f4b36 into PolkaGate:main Sep 23, 2024
5 checks passed
github-actions bot pushed a commit that referenced this pull request Sep 23, 2024
## [0.12.3](v0.12.2...v0.12.3) (2024-09-23)

### Bug Fixes

* fix useApi interaction with useApiWithChain2 ([#1556](#1556)) ([23f4b36](23f4b36))
@AMIRKHANEF AMIRKHANEF deleted the useApiPeopleChainIssue branch September 23, 2024 11:25
This was referenced Sep 24, 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.

bug: useApi does not work properly with useApiWithChain 2
2 participants