Currently facing an issue where I am trying to retrieve images from the backend using ReactQuery. Here is the ReactQuery code snippet:
export const useGetProductImagesByProductId = (productId: string) =>
useQuery({
queryKey: ['productImages', productId],
queryFn: async () =>
(await (await apiClient.get)<ProductImage[]>(`api/products/images/getImages/${productId}`)).data,
})
The problem arises when fetching the image URLs separately from my products, as they are not being rendered properly.
I display my products in the ProductItem Component:
function ProductItem({product}: {product: Product}){
const { data: images, isLoading: imagesLoading, error: imagesError } = useGetProductImagesByProductId(product.productId);
if (imagesLoading) return <div>Loading images...</div>;
if (imagesError) return <div>Error loading images: {imagesError.message}</div>;
const imageSrc = images && images.length > 0 ? images[0].imageUrl : '';
return(
<Card>
<Link to={'/product/' + product.productId}>
<img src={imageSrc} alt={product.name} className='product-image'/>
</Link>
<Card.Body>
<Link to={`/product/${product.productId}`}>
<Card.Title>{product.name}</Card.Title>
</Link>
</Card.Body>
</Card>
)
}
If I input the URL directly into the img
tag, it works fine:
<img src={"http://localhost:5045/Upload/Product/abeb7b1e-6705-454c-3316-08dc36b5c832/image.png"} alt={product.name} className='product-image'/>
EDIT 1
Upon testing, the array images
returns the complete array, but images[0]
and images[0].urlPath
both return undefined. As a temporary fix, I used this solution:
<img src={String(images && images[0])} alt={product.name} className='product-image'/>
EDIT 2 The structure of the ProductImage type is as follows:
export type ProductImage = {
imageUrl: string;
}