Reputation: 26732
I am caching a few images like:
Image.prefetch(`${remoteImageUrl}/100x100`)
Image.prefetch(`${remoteImageUrl}/800x800`)
Image.prefetch(`${remoteImageUrl}/1000x1000`)
While that is happening a component that wants to show the highest resolution version currently available may render.
if 1000 cached use 1000,
elseif 800 cached use 800,
elseif 100 cached use 100
How do I test "if 1000 is cached"?
I tried .complete this with no luck.
if (Image.prefetch(`${remoteImageUrl}/1000x1000`).complete) {}
How do you check the existence of a prefetched image in React Native?
Upvotes: 1
Views: 1162
Reputation: 84784
It doesn't look like this is possible using the out of the box APIs.
First of all, Image.prefetch
doesn't contain any other methods related to the prefetch cache.
Diving into the detail - on iOS, Image.prefetch
calls the native RCTImageViewManager.prefetchImage
method, which indirectly ends up loading the image and storing it in RCTImageCache
. Since there are no bridged functions that access the image cache directly, you're somewhat out of luck.
However, you could work around it by wrapping your calls to Image.prefetch
in a function that tracks which ones have completed:
// imagePrefetch.js
const prefetchedImages = {};
export function prefetchImage(url) {
return Image.prefetch(url)
.then(val => {
prefetchedImages[url] = true;
return val;
});
};
export function isPrefetched(url) {
return prefetchedImages[url] !== undefined;
}
Keep in mind that this is specifically a workaround for images you prefetch, not other images that happened to be cached from being loaded through other means.
Upvotes: 2