I have this simple app where I am showing images and also can add more. So when I add an image I show a spinner while it loads and then hide the spinner when its done loading. But the issue is when I'm adding the second image, the spinner doesn't show up. This is because of the boolean I'm using and I think it is being used globally.
Please note that I add an image through image url and rendering it with img html tag of course. I'm using RactiveJS and I feel like there is something I can do with an unique identifier but just dont know how. All the images have unique id attached to its data.
Here's the Ractive code:
let isImageLoaded = false;
const ractive = new Ractive({
el: '#container',
template: `
{{#each images}}
<div class="container">
{{#if !isImageLoaded}}
<span class="spinner"></span>
{{/if}}
<img
alt=""
src="{{url}}"
on-load="imageLoaded"
style="display: {{isImageLoaded ? 'block' : 'none'}};"
/>
</div>
{{/each}}
`,
data: {
images: [
{ id: 1, url: 'https://www.some-image.com/image1.jpg' },
],
isImageLoaded : isImageLoaded
}
});
ractive.on('imageLoaded', function(e) {
ractive.set('isImageLoaded', true);
});
function addImage(image) {
const allImages = ractive.get('images');
allImages.push(images);
ractive.set('isImageLoaded', false);
ractive.set('images', allImages);
}
If I set isImageLoaded to false in addImage function then adding a new image makes all the other spinners to show up.
How can I use ids to make each image and spinner unique and show spinner only when adding a new image?
You need to track for each image separately whether it has been loaded or not. One possible way is to turn
isImageLoadedinto an object, with image IDs as keys and booleans as values.