Image component - onerror fallback

Hello Community!

I am displaying thumbnail images for products in my app, which i get from a third party URL when constructing a string like: “productbase.no/produkt/{{productID}}/produktbilde”. However sometimes the URL returns broken formats or a 404.

Is there anyway to fallback to a placeholder image (a resource file) when the imageUrl fails? <img src={https://produktbase.no/produkt/${productID}/produktbilde}
onerror=“this.src=‘https://storage.googleapis.com/appfarm-public/.../placeholder.png’” /> something equivalent onerror in the html img tag.

Alt text only displays string and can’t render a image so that doesn’t solve it either.

Ive tried fetching the URL and checking the response in function editor, but that’s seems like an excessive solution, especially for 300k products. And ive ran into some complications with fetching async from client in function editor.

Any suggestions?

Best Regards,
Jakob

Hello!

That sound like a good feature request - I just subitted it!

Until then (might take some time to have the feature implemented), can you try to add a Coded Component instead, and put this HTML inside it?

<img src=“” onerror=“this.onerror=null; this.src=‘<URL to placeholder image here’;”/>

Thanks! Solved it with a coded component. This was the implementation for anyone interested:

HTML
<img id="productImage" style="width: 100%; height: auto;" alt="Product Image" />

JS

const { data, element } = appfarm;


const imageElement = element.querySelector(‘#productImage’);


const imageDataSource = data.primaryImageSource.get();
const productData = data.productInfo.get();


const primaryImageUrl = imageDataSource[0]?.imageURL
? imageDataSource[0].imageURL
: https://example.com/api/product/${productData}/image;


imageElement.src = primaryImageUrl;


imageElement.onerror = function() {
imageElement.src = “https://example.com/path/to/fallback-image.jpg”;
};
2 Likes