aboutsummaryrefslogtreecommitdiff
path: root/src/containers/PollCreation/useS3Preupload.ts
blob: ef3a4081463561a59be687484aa5130978dfcc6f (plain)
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
import { useState, useCallback, useMemo } from 'react';
import uploadFileToS3 from '../../utils/uploadFileToS3';


interface Hook {
  setValue: (value: File | string | undefined) => void;
  isReady: boolean;
  resolve: () => Promise<string>;
  progress: number;
}

export default (): Hook => {
  const [url, setUrl] = useState<string>();
  const [file, setFile] = useState<File>();
  const [progress, setProgress] = useState<number>(0);

  const isReady = useMemo(() => Boolean(file || url), [file, url]);

  const setValue: Hook['setValue'] = useCallback(value => {
    if (value instanceof File) {
      setFile(value);
      setUrl(undefined);
    } else {
      setUrl(value);
      setFile(undefined);
    }
  }, [setUrl, setFile]);

  const resolve = useCallback(async (quality?: number): Promise<string> => {
    if (file) return uploadFileToS3(file, quality, setProgress);
    return url || '';
  }, [file, url]);

  return {
    setValue,
    isReady,
    resolve,
    progress
  };
};