Created
January 18, 2018 14:58
-
-
Save matt-leonardo/e03e70086c0021ed640fa2b737079260 to your computer and use it in GitHub Desktop.
Caching Image in Expo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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