My app uses React.js and Node.js for backend. When the page is loaded all images are rendered sucessfully but when refreshing the page sometimes some images are not loaded. So this issue is inconsistent and affects random images when it happens.
Using Multer the application initially saves the images to local a folder (src/assets/uploaded_imgs) then saves in database the img path (for each entity). Using Axios the entities are obtained from DB through a custom hook, saved to a State and then mapped and rendered on the component.
The problem is being caused by the following structure I'm using:
const list = items.map((item) => {
return <div>
...
{
checkImg(item) ?
<img src={require(`../../${item.img_url}`)} alt="img cover" /> :
<img src='imageUnavailable.png' alt="Not provided" />
}
...
</div>
})
If I just use the <img src={require(`../../${item.img_url}`)} alt="img cover" /> instead of the ternary conditional there are no issues when refreshing but without it if the local image is moved or deleted, the application breaks.
The checkImg function serves to check if the image is there and if it's a valid file before importing it:
const checkImg = (item) => {
try {
const img = new Image()
img.src = require(`../../${item.img_url}`)
return img.complete && img.naturalWidth !== 0
} catch (error) {
return false
}
}
The app is still in delevopment so I didn't tested this issue in deployment in case this is important.
I searched suggestions on using a service worker or a lazy loading library but it looked overkill or a too complex implementation.
Can anyone tell me how to solve this issue? Please note that if there's a better solution than this ternary conditional I'm also interested.
Thanks in advance for any help.
A quick search led me to the suggestion in the link below, which I'm not if you've tried however I believe require is to be used only with static images and you mention storing it in a db and using the value from a saved state. Have you tried without the require. This is how I access images when using state.
<img src={item.img_url} alt="img cover" />In react, how do I use require for an image?