Last active
January 8, 2023 15:39
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example of using this hook: