Skip to content

Instantly share code, notes, and snippets.

@Shivendra30
Last active September 22, 2020 22:42
Show Gist options
  • Save Shivendra30/b5a0d82ae69e33087e9121c372727685 to your computer and use it in GitHub Desktop.
Save Shivendra30/b5a0d82ae69e33087e9121c372727685 to your computer and use it in GitHub Desktop.
A Image Caching component that I use in react-native show a thumbnail while image is being loaded and also download it to device to allow quick loading the next time
import React, {useState, useEffect} from 'react';
import {
Image,
View,
StyleSheet,
} from 'react-native';
import RNFetchBlob from 'rn-fetch-blob';
import isEmpty from '../../utils/is-empty';
import shorthash from 'shorthash';
const ProgressiveImage = props => {
const {thumbnailSource, source, style} = props;
const [imageUri, setImageUri] = useState(props.source.uri);
//Make an async useEffect (Picked from SO. Don't trust this code :p)
const useEffectAsync = (effect, inputs) => {
useEffect(() => {
effect();
}, inputs);
};
useEffectAsync(async () => {
if (!isEmpty(imageUri)) {
const uri = await downloadImage(imageUri);
setImageUri(uri);
}
}, []);
return (
<View style={styles.container}>
<Image
{...props}
source={thumbnailSource}
style={style}
blurRadius={2}
/>
<Image
{...props}
source={{uri: imageUri}}
style={[styles.imageOverlay, style]}
/>
</View>
);
};
const downloadImage = async imageUrl => {
let filename = `image-cache-${shorthash.unique(imageUrl)}`;
let path = RNFetchBlob.fs.dirs.DocumentDir + '/' + filename;
console.log('Checking if Image exists.....');
let uriToReturn = null;
try {
const exist = await RNFetchBlob.fs.exists(path);
console.log(`file ${exist ? '' : ' does not'} exist - ${path}`);
if (exist) uriToReturn = 'file://' + path;
else if (!exist) {
console.log('Downloading Image.....');
const res = await RNFetchBlob.config({
fileCache: true,
path,
}).fetch('GET', imageUrl, {});
uriToReturn = 'file://' + res.path();
}
} catch (err) {
console.log(err);
}
return uriToReturn;
};
const styles = StyleSheet.create({
imageOverlay: {
position: 'absolute',
left: 0,
right: 0,
bottom: 0,
top: 0,
},
container: {
// backgroundColor: '#e1e4e8',
},
});
export default ProgressiveImage;
const isEmpty = value => {
return (
value === null ||
value === undefined ||
(typeof value === 'object' && Object.keys(value).length === 0) ||
(typeof value === 'string' && value.trim().length === 0)
);
};
export default isEmpty;
@Shivendra30
Copy link
Author

Can you reproduce on CodePen?

@vikashth1
Copy link

@Shivendra30 I am not familiar with CodePen?

@Shivendra30
Copy link
Author

https://codepen.io/ - You can write your code here by choosing a react native environment. You can watch some YT videos to figure this out. Super easy

Once you do that, we can work on the same code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment