Reputation: 17
I have 7URL's out of which sometimes of 3-4 are valid downloadable Images.. so before rendering the Images using getPhotosList function I check the Valid download URL using function CheckValidImages
const CheckValidImages = async () => {
if (!props.location.state.isVideoContent) {
let getRecipeDetailWorkflowRead = {props.location.state.recipeDetailWorkflowRead};
let recipePhotos = [];
let sequence = 0;
for (var i = 0; i < getRecipeDetailWorkflowRead.recipePhotos.length; i++) {
const img = new Image();
img.src = getRecipeDetailWorkflowRead.recipePhotos[i].path;
await img
.decode()
.then(() => {
getRecipeDetailWorkflowRead.recipePhotos[i].sequence = sequence + 1;
recipePhotos.push(getRecipeDetailWorkflowRead.recipePhotos[i]);
sequence = sequence + 1;
})
.catch((encodingError) => {});
}
getRecipeDetailWorkflowRead.recipePhotos = recipePhotos;
setRecipeDetailWorkflowRead(getRecipeDetailWorkflowRead);
setImageLoader(false);
} else {
setRecipeDetailWorkflowRead(
props.location.state.recipeDetailWorkflowRead
);
}
};
const getPhotosList = () => {
if (recipeDetailWorkflowRead.recipePhotos !== undefined) {
console.log(recipeDetailWorkflowRead.recipePhotos);
var listItems = recipeDetailWorkflowRead.recipePhotos.map((el, i) => {
return (
<div
key={i}
className={['mr-1', Classes.imagediv].join(' ')}
draggable='true'
onDragEnd={dragEnd}
onDragStart={dragStart}
data-item={JSON.stringify(el)}
>
<img
className={i === 0 ? Classes.card_img_first : Classes.card_img}
src={el.path}
alt='cardimg'
/>
<div className={Classes.card_body}>
<input
type='text'
name='mediaDescription'
value={el.mediaDescription || ''}
onChange={(event) => onAltTextChangehandler(event, i)}
placeholder='Alt text'
className={['form-control', Classes.img_alt_text].join(' ')}
/>
</div>
</div>
);
});
return (
<div
onDragOver={dragOver}
className={['d-flex', 'flex-row', Classes.contain].join(' ')}
>
{listItems}
</div>
);
}
};
In CheckValidImage function getRecipeDetailWorkflowRead.recipePhotos[i].path has an Image path which I check if its valid or not. Now if the image is valid I try push it in recipePhotos and finally after all images path are checked I update the state setRecipeDetailWorkflowRead
But this seems much time consuming activity if the Image size is bigger. Can someone suggest any another alternate option where I can retrive the Images faster.
Upvotes: 0
Views: 2562
Reputation: 29214
I don't know about react, but with fetch I think you could do a 'HEAD' request and check the headers without downloading the content:
var url = 'https://nystudio107-ems2qegf7x6qiqq.netdna-ssl.com/img/blog/_1200x630_crop_center-center_82_none/craft-cms-custom-field-leveraging-platform-2.jpg?mtime=1598495914';
var p = fetch(url, { method: 'HEAD' });
p.then(r => {
if (r.status === 200 && r.headers.get('content-type') === 'image/jpeg')
{
console.log('Found an image! Size is:', r.headers.get('content-length'));
}
});
Upvotes: 0