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;
@brascene
Copy link

Awesome! I've also used this for ImageBackground, thanks!

@Shivendra30
Copy link
Author

Glad you found it valuable. Thanks a lot :)

@vikashth1
Copy link

Hello, I am new in react native how can I use your code can you please guide me where do I put these file?

@Shivendra30
Copy link
Author

Shivendra30 commented Jan 22, 2020

Sure, so when instead of using Image component in react-native like this,

<Image source={'<image-url>'} />

You can use CachedImage,

import CachedImage from "<path-to-file-where-you-place-CachedImage-component>"

<CachedImage source={'<image-url>'} />

@vikashth1
Copy link

@Shivendra30 Thank you for your response I tried as you suggested but I am getting the error Unable to resolve module shorthash from shorthash could not be found within the project.

Any suggestion?

@vikashth1
Copy link

@Shivendra30 I am able to fix this however I tried this on simulator but images are not loading.

Any suggestion?

@Shivendra30
Copy link
Author

Yeah sure.
shorthash is a module that you need to install

So just do npm install shorthash in your project directory

@vikashth1
Copy link

@Shivendra30 I am able to fix this however I tried this on simulator but images are not loading.

Any suggestion?

@vikashth1
Copy link

@Shivendra30 I see that image is downloading but not display on app

@vikashth1
Copy link

@Shivendra30 any idea?

@Shivendra30
Copy link
Author

@vikashth1 Sorry for the delayed response.

Well, are you trying to load local images by any chance? Or from a remote URL?

Can you help me with some more data? Screenshots, logs, etc?

@vikashth1
Copy link

@Shivendra30 Thank you so much for your response.

I am trying to load images from URL.

It's downloading the image but not displaying in the app just blank.

Do let me know if you need anything else.

@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