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
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/light-peaches-reflect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@nextui-org/use-image": patch
---

fix loading image after props changes (#4518)
13 changes: 13 additions & 0 deletions packages/hooks/use-image/__tests__/use-image.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,19 @@ describe("use-image hook", () => {
await waitFor(() => expect(result.current).toBe("loaded"));
});

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"));
});
wingkwong marked this conversation as resolved.
Show resolved Hide resolved

it("can handle error image", async () => {
mockImage.simulate("error");
const {result} = renderHook(() => useImage({src: "/test.png"}));
Expand Down
53 changes: 24 additions & 29 deletions packages/hooks/use-image/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import type {ImgHTMLAttributes, SyntheticEvent} from "react";

import {useRef, useState, useEffect, MutableRefObject} from "react";
import {useRef, useState, useEffect, useCallback} from "react";
import {useIsHydrated} from "@nextui-org/react-utils";
import {useSafeLayoutEffect} from "@nextui-org/use-safe-layout-effect";

Expand Down Expand Up @@ -66,7 +66,7 @@ type ImageEvent = SyntheticEvent<HTMLImageElement, Event>;
*/

export function useImage(props: UseImageProps = {}) {
const {onLoad, onError, ignoreFallback} = props;
const {onLoad, onError, ignoreFallback, src, crossOrigin, srcSet, sizes, loading} = props;

const isHydrated = useIsHydrated();

Expand Down Expand Up @@ -96,11 +96,31 @@ export function useImage(props: UseImageProps = {}) {
}
};

const load = useCallback((): Status => {
if (!src) return "pending";
if (ignoreFallback) return "loaded";

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;
wingkwong marked this conversation as resolved.
Show resolved Hide resolved
if (img.complete && img.naturalWidth) {
return "loaded";
}

return "loading";
}, [src, crossOrigin, srcSet, sizes, onLoad, onError, loading]);

useSafeLayoutEffect(() => {
if (isHydrated) {
setStatus(setImageAndGetInitialStatus(props, imageRef));
setStatus(load());
}
}, [isHydrated]);
}, [isHydrated, load]);

/**
* If user opts out of the fallback/placeholder
Expand All @@ -109,31 +129,6 @@ export function useImage(props: UseImageProps = {}) {
return ignoreFallback ? "loaded" : status;
}

function setImageAndGetInitialStatus(
props: UseImageProps,
imageRef: MutableRefObject<HTMLImageElement | null | undefined>,
): Status {
const {loading, src, srcSet, crossOrigin, sizes, ignoreFallback} = props;

if (!src) return "pending";
if (ignoreFallback) return "loaded";

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;
if (img.complete && img.naturalWidth) {
return "loaded";
}

return "loading";
}

export const shouldShowFallbackImage = (status: Status, fallbackStrategy: FallbackStrategy) =>
(status !== "loaded" && fallbackStrategy === "beforeLoadOrError") ||
(status === "failed" && fallbackStrategy === "onError");
Expand Down
Loading