Skip to content

Instantly share code, notes, and snippets.

@matt-leonardo
Created January 18, 2018 14:58
Show Gist options
  • Save matt-leonardo/e03e70086c0021ed640fa2b737079260 to your computer and use it in GitHub Desktop.
Save matt-leonardo/e03e70086c0021ed640fa2b737079260 to your computer and use it in GitHub Desktop.
Caching Image in Expo
import React from 'react';
import { Image } from 'react-native';
import { FileSystem } from 'expo';
import { hashOf } from '../../utils/';
class SmartImage extends React.PureComponent {
state = { source: this.props.source };
componentDidMount() {
this.mounted = true;
if (typeof this.props.source === 'number') {
return;
}
const remoteUri = this.props.source.uri;
const fileUri = FileSystem.documentDirectory + hashOf(remoteUri) + '.jpg';
FileSystem.getInfoAsync(fileUri)
.then(({ exists, uri }) => {
if (exists) {
this.loadCacheImage(uri);
} else {
FileSystem.downloadAsync(remoteUri, fileUri)
.catch(e => console.log(e));
}
}
);
}
componentWillUnmount() {
this.mounted = false;
}
loadCacheImage = (uri) => {
if (this.mounted) {
this.setState({ source: { uri } });
}
}
render() {
const newProps = { ...this.props, source: this.state.source };
return (
<Image {...newProps} />
);
}
}
export default SmartImage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment