How To Cache Image In React Native
I will show you save images in cache. We will use this library for save image: react-native-fs.
To start using file stream, first import react-native-fs:
import RNFS from 'react-native-fs';
Then we assign the path as a variable:
let CacheDir = RNFS.CachesDirectoryPath + '/';
Now we can use filestream to save the image to the cache. I will download image to the cache and then use “RNFS.downloadFile”. We need to set two parameters, “fromUrl” and “toFile”, “fromUrl” is the url address, we will set download path. “toFile” is the local address for downloaded image. We will set image url for “fromUrl” like this. And we set local path in “toFile”. Then this function should return value. We will use “promise” for return value. Return value is like this:
{"bytesWritten": 0, "jobId": 1, "statusCode": 200}
We will use the response to check if the process was successful. If “response.statusCode” is 200, we can return filePath because download process is successfully. The corresponding code is below:
function saveImageInCache(imageUrl, imageName) {
let filePath = CacheDir + imageName;
RNFS.downloadFile({
fromUrl: imageUrl,
toFile: filePath,
}).promise.then(response => {
if(response.statusCode == 200)
return filePath;
})
}
Great! We can call this function and use it in our app. If you want to get images any time, you can save image names, I recommend saving them as json in asyncstorage. For use, call (CacheDir + imageName) image location. If you would want to check exist image, you can use “RNFS.exists”,if the image is exist, it returns true otherwise it returns false, like this:
async function isExistImage(imagePath) {
await RNFS.exists(imagePath)
.then((exists) => {
return exists;
});
}