Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download and store images for offline use React Native

Tags:

react-native

I'm in the process of building an iOS application that will, when prompted by the user, fetch a large JSON file containing image URLs.

How can I download these images so that they will be available for use by my application even when it has no access to wifi/data?

like image 524
MWCD Avatar asked Jul 20 '16 13:07

MWCD


People also ask

How do I download images from React Native?

To download an image using rn-fetch-blob we will use the RNFetchBlob component which provides a fetch method with some different configuration. Here is the code snippet to download the image.

How save offline data in React Native?

To have offline-first functionality when the app is launched and there is no connection, you will need to add redux-persist to your app. This enables it to store a snapshot of the state of your app to the device's memory and rehydrate the state when the app is launched.

Where does React Native app store images?

Any images that you import in your React components should be stored close to where they are used (preferably in the same directory). Any images that you do not import in your React components (e.g. favicons ) should be stored in your public/ directory, e.g. under a favicons/ folder.

Can I work with react offline?

To make our app work offline, we need to get the web assets to work offline. Create React App already has the required boilerplate for making an app offline using service workers. Open src/index. js and change the line that says serviceWorker.


1 Answers

React Native has poor support to binary data, you are not be able to get the binary data directly via fetch. However you can use XMLHttpRequest in 0.30 branch or CameraRoll, refer to this post.

If you want to persist those image data, consider use AsyncStorage.

There're also several open source modules help you deal with file access if you want to store the images in file system.

react-native-fs

react-native-fetch-blob

NOTE: react-native-fetch-blob has been discontinued. rn-fetch-blob is a fork of it that is still maintained. When using npm, don't include react-native-fetch-blob but rn-fetch-blob instead.

like image 135
Xeijp Avatar answered Oct 16 '22 23:10

Xeijp