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

PCH Related Posts: Prevent Related Posts indefinite loading #2666

Merged
merged 5 commits into from
Jul 25, 2024

Conversation

vaurdan
Copy link
Contributor

@vaurdan vaurdan commented Jul 24, 2024

Description

This PR enhances the usePostData hook in the Related Posts feature by utilizing hasFinishedResolution and isResolving to ensure it returns data only when it's fully resolved. This update is particularly useful in scenarios where the users REST API endpoint is disabled, preventing the PCH from retrieving a list of users.

Testing indicates that the new approach ensures the hook accurately determines when the data is ready to be rendered, preventing the component from remaining indefinitely in a Loading state. The component will now attempt to render with the available data as soon as all fetching operations are resolved.

Motivation and context

Improve the reliability of the Related Posts feature, ensuring it functions correctly even in edge cases or when unexpected API data is returned. By checking if the data has been resolved, the feature can gracefully handle scenarios where certain data endpoints, such as the users REST API, are disabled or slow to respond. This prevents the application from hanging indefinitely and enhances the user experience by rendering available data promptly.

How has this been tested?

Tested locally.

Summary by CodeRabbit

  • New Features
    • Introduced a timeout mechanism in the post data fetching process, allowing for improved handling of delays. Users can now specify a timeout duration for fetching related post data, enhancing overall performance and responsiveness.

@vaurdan vaurdan added this to the 3.16.2 milestone Jul 24, 2024
@vaurdan vaurdan self-assigned this Jul 24, 2024
@vaurdan vaurdan requested a review from a team as a code owner July 24, 2024 10:55
Copy link
Contributor

coderabbitai bot commented Jul 24, 2024

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Base branches to auto review (4)
  • develop
  • add/.*
  • fix/.*
  • update/.*

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

Walkthrough

The recent updates to the usePostData function enhance its robustness by introducing a timeout mechanism for fetching post data. With the addition of a timeoutDurationMs parameter, the function can now manage data retrieval more effectively, ensuring that it returns post details even if the fetching process is delayed. This improves user experience by allowing the application to handle slow network responses gracefully.

Changes

Files Change Summary
src/content-helper/editor-sidebar/related-posts/hooks.ts Modified usePostData to include a timeoutDurationMs parameter for managing fetch timeouts. Added state variables isTimeout and postData to track fetching status and results. Introduced two useEffect hooks for managing data readiness and timeout conditions.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Component
    participant usePostData
    participant DataStore

    User->>Component: Request post data
    Component->>usePostData: Call usePostData(timeoutDurationMs)
    usePostData->>DataStore: Fetch post data (authors, categories, tags)
    alt Data fetched before timeout
        DataStore-->>usePostData: Return post data
        usePostData-->>Component: Provide post data
    else Timeout reached
        Note right of usePostData: Set isTimeout to true
        usePostData-->>Component: Provide partial post data
    end
Loading

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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.

@vaurdan
Copy link
Contributor Author

vaurdan commented Jul 24, 2024

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Jul 24, 2024

Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

Outside diff range, codebase verification and nitpick comments (5)
src/content-helper/editor-sidebar/related-posts/hooks.ts (5)

7-7: Ensure compliance with WordPress coding standards.

The import statement for useEffect and useState should be alphabetically ordered with other imports for better readability.

- import { useEffect, useState } from '@wordpress/element';
+ import { useEffect, useState } from '@wordpress/element';

40-40: Add a period at the end of the comment.

The comment should end with a period to adhere to documentation standards.

- * @since 3.16.2 Added a timeout to ensure the hook returns after X seconds.
+ * @since 3.16.2. Added a timeout to ensure the hook returns after X seconds.

44-46: Clarify the parameter description.

The description for timeoutDurationMs could be more concise and clear.

- * @param {number} timeoutDurationMs The duration in milliseconds before the hook times out and
- *                                   returns the data as is.
+ * @param {number} timeoutDurationMs The duration in milliseconds before the hook times out and returns the data as is.

49-49: Ensure compatibility with WordPress coding standards.

The function signature should include a space before the default parameter value for better readability.

- export function usePostData( timeoutDurationMs: number = 200 ): PostData {
+ export function usePostData( timeoutDurationMs: number = 200 ): PostData {

58-63: Ensure the JSDoc comment is accurate and complete.

The JSDoc comment for the postAttributes function is well-written but ensure it includes a period at the end.

- * @since 3.14.4
+ * @since 3.14.4.
Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between be3bfd8 and 0b83ed9.

Files ignored due to path filters (2)
  • build/content-helper/editor-sidebar.asset.php is excluded by !build/**
  • build/content-helper/editor-sidebar.js is excluded by !build/**
Files selected for processing (1)
  • src/content-helper/editor-sidebar/related-posts/hooks.ts (3 hunks)
Additional context used
Path-based instructions (1)
src/content-helper/editor-sidebar/related-posts/hooks.ts (1)

Pattern **/*.{js,ts,tsx,jsx}: "Perform a detailed review of the provided code with following key aspects in mind:

  • Review the code to ensure it is well-structured and adheres to best practices.
  • Verify compliance with WordPress coding standards.
  • Ensure the code is well-documented.
  • Check for security vulnerabilities and confirm the code is secure.
  • Optimize the code for performance, removing any unnecessary elements.
  • Validate JSDoc comments for accuracy, currency, and adherence to WordPress coding standards.
  • Ensure each line comment concludes with a period.
  • Confirm every JSDoc comment includes a @SInCE tag indicating the next version of the plugin to include the code.
  • Guarantee compatibility with the latest version of WordPress, avoiding deprecated functions or features."
Additional comments not posted (5)
src/content-helper/editor-sidebar/related-posts/hooks.ts (5)

50-56: Initialize state variables correctly.

The state variables isTimeout and postData are initialized correctly. Ensure that these states are managed properly throughout the function.


Line range hint 64-104:
Verify the correctness of the useSelect hook logic.

The logic within the useSelect hook appears to be correct. Ensure that the getEntityRecords function is used correctly and that the data is fetched as expected.


106-134: Ensure the useEffect hook handles state updates correctly.

The useEffect hook updates the postData state when all data is ready or when the timeout is reached. Ensure that the dependencies are correctly specified.


136-147: Ensure the timeout logic is correctly implemented.

The second useEffect hook sets a timeout to update the isTimeout state. Ensure that the timeout is cleared correctly to avoid memory leaks.


149-149: Return the post data correctly.

The function returns the postData state correctly. Ensure that the returned data is used appropriately in the consuming components.

Copy link
Collaborator

@acicovic acicovic left a comment

Choose a reason for hiding this comment

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

Interesting way to tackle this, I like it 🙂

I haven't tested, but if we're hitting WP endpoints by issuing HTTP requests, my gut feeling tells me that 200ms might be too low (e.g. high latency or heavy sites), and that we should raise it if it could be disruptive to user experience.

src/content-helper/editor-sidebar/related-posts/hooks.ts Outdated Show resolved Hide resolved
src/content-helper/editor-sidebar/related-posts/hooks.ts Outdated Show resolved Hide resolved
@vaurdan
Copy link
Contributor Author

vaurdan commented Jul 24, 2024

@acicovic I agree with you, I am a bit torn here, since this timeout will prevent the filter type UI from rendering for that amount of time, if any of the HTTP requests take to long or fail. Unfortunately, since we're doing the HTTP requests using Gutenberg's getEntityRecords, we don't have control/access to the requests, and it's not possible to check if they have either returned an error code, or if they are still running.

Although, and I tested this by throttling the connection in Chrome, if the endpoint is taking too long to respond, when it finally returns a valid response, the component will re-render and work as expected. But I think I agree with you that 200ms might be on the short side.

For how long do you suggest waiting? 500ms?

@acicovic
Copy link
Collaborator

If I understand correctly, this timeout will only slow down users when there's a problem (e.g blocked user endpoint). This system will not affect websites that work as expected. So, not all users will be forced to wait for these 200ms.

If the above is correct, in my opinion even waiting 1 second should be fine, since there would be an infinite freeze anyway if this fix wasn't in place. What I'm afraid of is introducing re-renders in configurations that work fine currently, and then having issues regarding that. If the user is using the tool while the re-rendering takes place, it could lead to a weird UX experience.

@vaurdan
Copy link
Contributor Author

vaurdan commented Jul 24, 2024

I might have found a way to tackle this using hasFinishedResolution and isResolving, from the core-data store. I will see if I can implement a better solution, and perhaps ditch the need for a timeout :)

@vaurdan
Copy link
Contributor Author

vaurdan commented Jul 25, 2024

@acicovic I changed the logic for the usePostData hook, and now instead of relying on the timeout, we're using hasFinishedResolution and isResolving to check if the data we need is actually ready to be used.

This has fixed the issue of having the UI waiting for the timeout before rendering the filter type Group Toggle, when one of the resolution fails. So it feels nearly instantaneous now :)

@acicovic acicovic changed the title PCH Related Posts: Add timeout mechanism to usePostData hook to prevent indefinite loading PCH Related Posts: Prevent revent indefinite loading Jul 25, 2024
@vaurdan vaurdan changed the title PCH Related Posts: Prevent revent indefinite loading PCH Related Posts: Prevent Related Posts indefinite loading Jul 25, 2024
Copy link
Collaborator

@acicovic acicovic left a comment

Choose a reason for hiding this comment

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

Looks good! Thank you!

src/content-helper/editor-sidebar/related-posts/hooks.ts Outdated Show resolved Hide resolved
src/content-helper/editor-sidebar/related-posts/hooks.ts Outdated Show resolved Hide resolved
@vaurdan vaurdan merged commit 9c13016 into prepare/3.16.2 Jul 25, 2024
34 checks passed
@vaurdan vaurdan deleted the update/related-posts-post-data-handling branch July 25, 2024 09:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants