Reputation: 137
Despite uploading a new image to an s3 hosted url, the <Image>
component will not update the image if the uri does not change. This is a problem for Android only as far as I can tell, because for iOS you can use the cache: 'reload'
prop.
I have resorted to this solution:
<Image
source={uri: imageUrlFromS3 + '?time=' + new Date(), cache: 'reload'}
style={width: 100, height: 100}
/>
By adding a meaningless query to the url, the component recognizes that the uri has changed, which then refreshes the updated image. Similarly, I have tried this by changing the key to be a new Date(). This seems like horrible for performance, due to the aggressive rerendering.
It seems that this has been a problem for a long time.
I have seen some answers that require using another package.
Is there another solution to this problem that doesn't require using another package?
Upvotes: 1
Views: 2111
Reputation: 36
Instead of concatenating the current Date prop, what you can do is create a state that takes the value of a random number whether you execute the query (the one that updates the image) and concatenate that to the uri, like this:
// state to notify the updating image process
const [onUpdateImage, setOnUpdateImage] = useState(Math.random())
// Function that updates the image
const updateImageQuery = () => {
...
setOnUpdateImage(Math.random())
}
//Image Display:
<Image style={{ width: 133, height: 133, }}
source={{
uri: image_URL + "?" + onUpdateImage
}}
/>
This way you can optimize the App performance and do the image re-rendering only when it's necessary. If the image is exposed in other screens, you can create onUpdateImage as a Context and use it globally.
Hope this helps you!
Upvotes: 2
Reputation: 63
You can substring the unix timestamp such that it could re-render every N milliseconds.
For example, source={uri: imageUrlFromS3 + '?' + Date.now().toString().substring(0,10) + "000" ...
would mean it would re-render every 1000 milliseconds = 1 second.
Upvotes: 0
Reputation: 1
You just have to do it like this:
source={uri: imageUrlFromS3 + '?' + new Date()}
Upvotes: 0