@@ -7,47 +7,45 @@ export interface URISource {
7
7
8
8
/**
9
9
* @param source either a remote URL or a local file resource.
10
- * @returns original image dimensions (width and height ).
10
+ * @returns original image dimensions (width, height and aspect ratio ).
11
11
*/
12
12
function useImageDimensions ( source : ImageRequireSource | URISource ) {
13
- const localAsset = typeof source === 'number'
14
- const [ dimensions , setDimensions ] = useState <
15
- | {
16
- width : number
17
- height : number
18
- }
19
- | undefined
20
- > ( localAsset ? Image . resolveAssetSource ( source ) : undefined )
21
- const [ error , setError ] = useState < Error > ( )
13
+ const [ [ dimensions , error ] , setState ] = useState <
14
+ [ { width : number ; height : number } ?, Error ?]
15
+ > ( [ ] )
16
+
22
17
useEffect ( ( ) => {
23
- if ( localAsset ) {
24
- return
25
- }
26
18
try {
27
- Image . getSize (
28
- ( source as URISource ) . uri ,
29
- ( width , height ) => setDimensions ( { width, height} ) ,
30
- e => {
31
- throw e
32
- } ,
33
- )
19
+ if ( typeof source === 'number' ) {
20
+ const { width, height} = Image . resolveAssetSource ( source )
21
+ setState ( [ { width, height} ] )
22
+ } else if ( typeof source === 'object' && source . uri ) {
23
+ setState ( [ ] )
24
+ Image . getSize (
25
+ source . uri ,
26
+ ( width , height ) => setState ( [ { width, height} ] ) ,
27
+ e => setState ( [ dimensions , e ] ) ,
28
+ )
29
+ } else {
30
+ throw new Error ( 'not implemented' )
31
+ }
34
32
} catch ( e ) {
35
- setError ( e )
33
+ setState ( [ dimensions , e ] )
36
34
}
37
- } , [ source , localAsset ] )
35
+ // eslint-disable-next-line react-hooks/exhaustive-deps
36
+ } , [ source ] )
38
37
39
38
return {
40
- dimensions,
41
- error,
42
- /**
43
- * width to height ratio
44
- */
45
- get aspectRatio ( ) {
46
- return dimensions && dimensions . width / dimensions . height
39
+ dimensions : dimensions && {
40
+ ...dimensions ,
41
+ /**
42
+ * width to height ratio
43
+ */
44
+ get aspectRatio ( ) : number {
45
+ return this . width / this . height
46
+ } ,
47
47
} ,
48
- /**
49
- * loading indicator for remote image
50
- */
48
+ error,
51
49
get loading ( ) {
52
50
return ! dimensions && ! error
53
51
} ,
0 commit comments