S
SolidJS10mo ago
robert_

Suggestions for refactoring an async image component?

Hi, I've written a small async image wrapper for a project I'm working on, and I'm wondering if anybody has any suggestions for helping me refactor my component, so that it doesn't feel so... off...
import { join } from "path";
import { type Component, lazy } from "solid-js";

type ModuleType = typeof import(/* @vite-ignore */ "../assets/blue-grey.png" );
type Props = { src: string, alt?: string, ext?: string; };

const assetDir = ( assetName: string ): string => join( "../assets", assetName );
const assetFile = ( assetName: string, ext: string ): string => assetName.concat( ".".concat( ext ) );
const findAsset = ( assetName: string, ext = "png" ) => assetDir( assetFile( assetName, ext ) );

const AsyncImage: Component<Props> = ( { src, alt, ext } ) => lazy( async () => {
const { default: image }: ModuleType = await import(/* @vite-ignore */ findAsset( src, ext ) );

return ( {
default: () => (
alt && (
<img src={ image.src } alt={ alt as string } width="100%" height="100%" />
) || (
<img src={ image.src } width="100%" height="100%" />
)
)
} );
} )();

export default AsyncImage;
import { join } from "path";
import { type Component, lazy } from "solid-js";

type ModuleType = typeof import(/* @vite-ignore */ "../assets/blue-grey.png" );
type Props = { src: string, alt?: string, ext?: string; };

const assetDir = ( assetName: string ): string => join( "../assets", assetName );
const assetFile = ( assetName: string, ext: string ): string => assetName.concat( ".".concat( ext ) );
const findAsset = ( assetName: string, ext = "png" ) => assetDir( assetFile( assetName, ext ) );

const AsyncImage: Component<Props> = ( { src, alt, ext } ) => lazy( async () => {
const { default: image }: ModuleType = await import(/* @vite-ignore */ findAsset( src, ext ) );

return ( {
default: () => (
alt && (
<img src={ image.src } alt={ alt as string } width="100%" height="100%" />
) || (
<img src={ image.src } width="100%" height="100%" />
)
)
} );
} )();

export default AsyncImage;
1 Reply
bigmistqke
bigmistqke10mo ago
why not
const AsyncImage: Component<Props> = ({ src, alt, ext }) => {
const [resource] = createResource(() => import(findAsset(src, ext)))
return <img src={resource()?.src} alt={alt} width="100%" height="100%"/>
}
const AsyncImage: Component<Props> = ({ src, alt, ext }) => {
const [resource] = createResource(() => import(findAsset(src, ext)))
return <img src={resource()?.src} alt={alt} width="100%" height="100%"/>
}
? and then wrap it in <Suspense/> if needed
Want results from more Discord servers?
Add your server