Image.prefetch not cacheing urls

Hi,

I am trying to understand how to cache an Image url so that it does not need to be redownloaded.
I have taken a look at: https://docs.expo.io/versions/v19.0.0/guides/preloading-and-caching-assets.html
and have been using Image.prefetch like so:

            const prefetchedImages = images.map(url => {
              console.log('url', url) //this is correctly logging the url
              return Image.prefetch(url)
            });
            Promise.all(prefetchedImages)
                .then(() => {
                    this.setState({loaded:true})
            })

This ultimately does set the state as true. I am then rendering my Images in a different component, but made sure the component that is prefetching does not unmount:

<Image source={{uri: myImageUrl}} style={{width:100, height:100}} />

When I load images into my grid view, only the local images appear right away, and the ones with URLs are white for a moment before rendering. Am I missing something here? I thought I can call my Image source as usual and the system will know to grab the cached image for that url.

Edit: When using cache:‘force-cache’ on iOS, the images are in fact loaded from cache. I thought I did not need to do that if I used prefetch.

1 Like

Try using force-cache in your image

<Image source={{uri: 'uri.com/img.jpg', cache: 'force-cache'}} />

I have no idea why this is necessary, but it seems to work for me.

Also make sure that your prefetch function doesn’t run more than once, as it will prefetch from the source every time it runs (even if it’s already cached). I use redux to keep track of what URL’s I’ve already cached, along with time accessed, and prefetch them again if a week has gone by.

2 Likes