-
Notifications
You must be signed in to change notification settings - Fork 306
/
Copy pathuseUploadFile.ts
62 lines (58 loc) · 1.64 KB
/
useUploadFile.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
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
import {
StorageError,
StorageReference,
uploadBytesResumable,
UploadMetadata,
UploadResult,
UploadTaskSnapshot,
} from 'firebase/storage';
import { useCallback, useState } from 'react';
export type UploadFileHook = [
(
storageRef: StorageReference,
data: Blob | Uint8Array | ArrayBuffer,
metadata?: UploadMetadata | undefined
) => Promise<UploadResult | undefined>,
boolean,
UploadTaskSnapshot | undefined,
StorageError | undefined
];
export default (): UploadFileHook => {
const [error, setError] = useState<StorageError>();
const [uploading, setUploading] = useState<boolean>(false);
const [snapshot, setSnapshot] = useState<UploadTaskSnapshot>();
const uploadFile = useCallback(
async (
storageRef: StorageReference,
data: Blob | Uint8Array | ArrayBuffer,
metadata?: UploadMetadata | undefined
): Promise<UploadResult | undefined> => {
return new Promise((resolve, reject) => {
setUploading(true);
setError(undefined);
const uploadTask = uploadBytesResumable(storageRef, data, metadata);
uploadTask.on(
'state_changed',
(snapshot) => {
setSnapshot(snapshot);
},
(error) => {
setUploading(false);
setError(error);
resolve(undefined);
},
() => {
setUploading(false);
setSnapshot(undefined);
resolve({
metadata: uploadTask.snapshot.metadata,
ref: uploadTask.snapshot.ref,
});
}
);
});
},
[]
);
return [uploadFile, uploading, snapshot, error];
};