-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
51 lines (45 loc) · 1.18 KB
/
index.js
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
import React, { useState, useEffect } from 'react';
export const useImageCache = (config) => {
const [ images, setImages ] = useState({});
const clearCache = () => setImages({});
const setCache = (x) => {
const isArray = Array.isArray(x);
if (!isArray && typeof x !== 'string') {
return console.error('[use-image-cache] Invalid src type');
}
const baseSet = new Set([...Object.keys(images), ...(isArray ? x : [x])]);
baseSet.forEach((src) => {
if (images[src]) return null;
const img = new Image();
img.onload = () => setImages(
{
...images,
[src]: {
src,
width: img.width,
height: img.height,
image: img,
loaded: true,
error: false,
},
}
);
img.onerror = () => setImages(
{
...images,
[src]: {
src,
image: img,
loaded: false,
error: true,
}
}
)
img.src = src;
return src;
});
}
useEffect(() => setCache(config), [config]);
return [images, setCache, clearCache];
};
export default useImageCache;