Skip to content

Instantly share code, notes, and snippets.

@sslotsky
Last active January 8, 2023 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sslotsky/0f1446613d217e5eb687536816a4218f to your computer and use it in GitHub Desktop.
Save sslotsky/0f1446613d217e5eb687536816a4218f to your computer and use it in GitHub Desktop.
A qwik hook for managing blurry image fallbacks. Computes the blurry image URL until the high-res image is ready to display.
import {
useResource$,
useSignal,
useTask$,
ResourceReturn,
} from "@builder.io/qwik";
import { MasonryPhoto } from "~/trcp/router";
export type State = "blank" | "blurry" | "done";
export function useImageUrl(store: {
file: MasonryPhoto;
}): ResourceReturn<string> {
const state = useSignal<State>("blank");
useTask$(({ track }) => {
track(() => store.file);
state.value = "blank";
});
const image = useResource$<string>(async ({ track }) => {
track(() => state.value);
const img = new Image();
if (state.value === "blank") {
img.src = store.file.fullSizeBlurUrl;
state.value = "blurry";
} else {
img.src = store.file.fullSizeUrl;
await img.decode();
state.value = "done";
}
return img.src;
});
return image;
}
@sslotsky
Copy link
Author

sslotsky commented Jan 8, 2023

Example of using this hook:

  const url = useImageUrl(store);

  return (
    <>
      {url.value.then((imgUrl) => (
        <img src={imgUrl} />
      ))}
    </>
  )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment