-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCachedImage.tsx
More file actions
69 lines (61 loc) · 1.73 KB
/
Copy pathCachedImage.tsx
File metadata and controls
69 lines (61 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import React, { Component } from 'react';
import { Image } from 'react-native';
import * as FileSystem from 'expo-file-system';
import * as Crypto from 'expo-crypto';
class CacheImage extends React.Component {
state = {
imgURI: ''
}
async componentDidMount() {
const filesystemURI = await this.getImageFilesystemKey(this.props.source.uri);
await this.loadImage(filesystemURI, this.props.source.uri);
}
async componentDidUpdate() {
const filesystemURI = await this.getImageFilesystemKey(this.props.source.uri);
if (this.props.source.uri === this.state.imgURI ||
filesystemURI === this.state.imgURI) {
return null;
}
await this.loadImage(filesystemURI, this.props.source.uri);
}
async getImageFilesystemKey(remoteURI) {
const hashed = await Crypto.digestStringAsync(
Crypto.CryptoDigestAlgorithm.SHA256,
remoteURI
);
return `${FileSystem.cacheDirectory}${hashed}`;
}
async loadImage(filesystemURI, remoteURI) {
try {
const metadata = await FileSystem.getInfoAsync(filesystemURI);
if (metadata.exists) {
console.log("use cached image")
this.setState({
imgURI: filesystemURI
});
return;
}
console.log("download image")
const imageObject = await FileSystem.downloadAsync(
remoteURI,
filesystemURI
);
this.setState({
imgURI: imageObject.uri
});
}
catch (err) {
console.log('Image loading error:', err);
this.setState({ imgURI: remoteURI });
}
}
render() {
return (
<Image
{...this.props}
source={this.state.imgURI ? { uri: this.state.imgURI } : null}
/>
);
}
}
export default CacheImage;