forked from CSFrequency/react-firebase-hooks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
useDownloadURL.ts
36 lines (31 loc) · 994 Bytes
/
useDownloadURL.ts
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
import {
getDownloadURL,
StorageError,
StorageReference,
} from 'firebase/storage';
import { useEffect } from 'react';
import { LoadingHook, useComparatorRef, useLoadingValue } from '../util';
export type DownloadURLHook = LoadingHook<string, StorageError>;
export default (storageRef?: StorageReference | null): DownloadURLHook => {
const { error, loading, reset, setError, setValue, value } = useLoadingValue<
string,
StorageError
>();
const ref = useComparatorRef(storageRef, isEqual, reset);
useEffect(() => {
if (!ref.current) {
setValue(undefined);
return;
}
getDownloadURL(ref.current).then(setValue).catch(setError);
}, [ref.current]);
return [value, loading, error];
};
const isEqual = (
v1: StorageReference | null | undefined,
v2: StorageReference | null | undefined
): boolean => {
const bothNull: boolean = !v1 && !v2;
const equal: boolean = !!v1 && !!v2 && v1.fullPath === v2.fullPath;
return bothNull || equal;
};