How to Cache Image and Other Assets

#1

I am fully aware that it’s not possible to bundle assets with compiled/built app at the moment. However, my app is primarily used offline in locations where the internet is extremely slow and expensive. There should at least be a method to cache all the required assets in local machine when the app runs for the first time, but I am not aware of any.

These links don’t help either:
https://docs.expo.io/versions/v16.0.0/sdk/asset.html
https://docs.expo.io/versions/v16.0.0/guides/assets.html

Any suggestions or example code would be appreciated.

Thanks

1 Like
#2

Hey, you’re right that this is just a missing feature right now, specifically bundling assets for the very first load. Right now you need at least one load with internet in order to cache everything. It’s something we’d like to work on when we have time.

#3

Thanks for the reply, and I totally understand that it’s the missing feature that’s on the road :wink: I just want to make sure of two things:

  1. Are all the assets that were successfully loaded cached for offline use?
  2. If so, would the cached assets be used when online as well, or would the assets be downloaded again?

I just don’t my app users to pay for expensive mobile data every single time they launch my app. That’s all.

Thank you for your help!

#4

For (1), use downloadAsync: https://docs.expo.io/versions/v16.0.0/sdk/asset.html#downloadasync to make sure they’re written to the device cache. There should be an example of this in our starter project.

@nikki can you clarify the answer to #2?

#5

@ben I’m also interested in finding out about this. I’m eating up more bandwidth than I’d like for my image hosting, it would help a lot if web images could be cached and served from the device instead.

To clarify, in my case the images are user-configurable (i.e. they can add/remove images that are then uploaded), so maybe what I’m asking for is different, as I’m not using Expo.Asset, just an Image component

#6

@pchon Yup, when you rerun your app and are online it will still use the caches.

#7

@buishi in your case if it’s an arbitrary remote URL and not a require('path/to/img') you can use the FS API directly to download as in https://github.com/expo/expo-sdk/blob/master/src/Asset.js#L118-L126

Planning to make this API more user-facing in future.

#8

I wrote a story on things you ought to know if you are caching images locally with expo at https://medium.com/@wcandillon/5-things-to-know-about-images-react-native-69be41d2a9ee