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(use-image): load images after props change #4523

Open
wants to merge 5 commits into
base: canary
Choose a base branch
from

Conversation

wingkwong
Copy link
Member

@wingkwong wingkwong commented Jan 9, 2025

Closes #4518

📝 Description

⛳️ Current behavior (updates)

🚀 New behavior

no source initially -> set source after seconds

pr4523-no-src.webm

💣 Is this a breaking change (Yes/No):

📝 Additional Information

Summary by CodeRabbit

  • Bug Fixes

    • Resolved an issue with image loading in the @nextui-org/use-image package
    • Improved handling of image prop changes, ensuring correct loading behavior
  • Tests

    • Added a new test case to verify image loading when source changes dynamically

The changes enhance the reliability of image loading functionality, addressing potential issues with prop updates and providing more robust image handling.

@wingkwong wingkwong added this to the v2.6.12 milestone Jan 9, 2025
Copy link

linear bot commented Jan 9, 2025

Copy link

vercel bot commented Jan 9, 2025

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

Name Status Preview Comments Updated (UTC)
nextui-docs-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 9, 2025 4:24pm
nextui-storybook-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 9, 2025 4:24pm

Copy link
Contributor

coderabbitai bot commented Jan 9, 2025

Walkthrough

The pull request addresses an issue with the @nextui-org/use-image hook related to image loading when the source (src) changes from null or undefined. The changes modify the hook's implementation to better handle dynamic image source updates, ensuring that the image loading mechanism works correctly when props are changed after initial rendering.

Changes

File Change Summary
packages/hooks/use-image/src/index.ts - Added load function using useCallback
- Refactored image loading logic
- Removed setImageAndGetInitialStatus function
packages/hooks/use-image/__tests__/use-image.test.tsx - Added new test case for handling image source changes

Assessment against linked issues

Objective Addressed Explanation
Fix image not loading when src changes from null/undefined
Ensure correct handling of image loading state

Possibly related PRs

Suggested reviewers

  • jrgarciadev

Finishing Touches

  • 📝 Generate Docstrings

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.

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

changeset-bot bot commented Jan 9, 2025

🦋 Changeset detected

Latest commit: c72c1b2

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 5 packages
Name Type
@nextui-org/use-image Patch
@nextui-org/avatar Patch
@nextui-org/image Patch
@nextui-org/user Patch
@nextui-org/react Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

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 (3)
packages/hooks/use-image/src/index.ts (2)

99-117: Review useCallback dependencies

The onLoad and onError callbacks are included in the dependencies array but aren't used within the load function. This could cause unnecessary re-renders.

-  }, [src, crossOrigin, srcSet, sizes, onLoad, onError, loading]);
+  }, [src, crossOrigin, srcSet, sizes, loading]);

112-114: Add naturalHeight check for complete image validation

The complete image validation should check both naturalWidth and naturalHeight to ensure the image is fully loaded.

-    if (img.complete && img.naturalWidth) {
+    if (img.complete && img.naturalWidth && img.naturalHeight) {
       return "loaded";
     }
.changeset/light-peaches-reflect.md (1)

1-5: Enhance changeset description

Consider adding more details about the specific changes and their impact:

 ---
 "@nextui-org/use-image": patch
 ---
 
-fix loading image after props changes (#4518)
+fix: handle image loading when src changes from undefined/null (#4518)
+
+- Added new load function to handle dynamic src changes
+- Improved image cleanup to prevent memory leaks
+- Added test coverage for dynamic src updates
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between eada8cb and c72c1b2.

📒 Files selected for processing (3)
  • .changeset/light-peaches-reflect.md (1 hunks)
  • packages/hooks/use-image/__tests__/use-image.test.tsx (1 hunks)
  • packages/hooks/use-image/src/index.ts (3 hunks)

Comment on lines +30 to +41
it("can handle changing image", async () => {
const {result, rerender} = renderHook(() => useImage({src: undefined}));

expect(result.current).toEqual("pending");

setTimeout(() => {
rerender({src: "/test.png"});
}, 3000);

mockImage.simulate("loaded");
await waitFor(() => expect(result.current).toBe("loaded"));
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve test reliability by controlling async operations

The current test implementation might be flaky due to race conditions between the setTimeout and image load simulation. Consider using Jest's timer mocks to control the timing precisely.

Here's a more reliable implementation:

   it("can handle changing image", async () => {
     const {result, rerender} = renderHook(() => useImage({src: undefined}));
 
     expect(result.current).toEqual("pending");
 
-    setTimeout(() => {
-      rerender({src: "/test.png"});
-    }, 3000);
+    // Use Jest's fake timers
+    jest.useFakeTimers();
+    
+    // Schedule the src change
+    setTimeout(() => rerender({src: "/test.png"}), 3000);
+    
+    // Fast-forward timers
+    jest.runAllTimers();
 
     mockImage.simulate("loaded");
     await waitFor(() => expect(result.current).toBe("loaded"));
+    
+    // Cleanup
+    jest.useRealTimers();
   });

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +103 to +111
const img = new Image();

img.src = src;
if (crossOrigin) img.crossOrigin = crossOrigin;
if (srcSet) img.srcset = srcSet;
if (sizes) img.sizes = sizes;
if (loading) img.loading = loading;

imageRef.current = img;
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Potential memory leak in image creation

The new Image instance should be cleaned up when the src changes to prevent memory leaks, especially in scenarios with rapid prop changes.

Consider adding cleanup logic:

   const load = useCallback((): Status => {
     if (!src) return "pending";
     if (ignoreFallback) return "loaded";
 
+    // Cleanup previous image if exists
+    if (imageRef.current) {
+      imageRef.current.onload = null;
+      imageRef.current.onerror = null;
+    }
+
     const img = new Image();
 
     img.src = src;
     if (crossOrigin) img.crossOrigin = crossOrigin;
     if (srcSet) img.srcset = srcSet;
     if (sizes) img.sizes = sizes;
     if (loading) img.loading = loading;
 
     imageRef.current = img;

Committable suggestion skipped: line range outside the PR's diff.

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] - Changing Image src from null fails to update
1 participant