aboutsummaryrefslogtreecommitdiff
path: root/src/hooks
diff options
context:
space:
mode:
authoreug-vs <eug-vs@keemail.me>2020-08-14 01:25:56 +0300
committereug-vs <eug-vs@keemail.me>2020-08-14 01:25:56 +0300
commit60583c1496aeaf366087bff550da8e9288ff33cf (patch)
treeef3700567800ec128db978be326ae178d2197e35 /src/hooks
parentd7aba191cdfbf6f2f5e35bcaa94e011fafcde3dc (diff)
downloadwhich-ui-60583c1496aeaf366087bff550da8e9288ff33cf.tar.gz
refactor: add useS3Preupload hook
Diffstat (limited to 'src/hooks')
-rw-r--r--src/hooks/useS3Preupload.tsx48
1 files changed, 48 insertions, 0 deletions
diff --git a/src/hooks/useS3Preupload.tsx b/src/hooks/useS3Preupload.tsx
new file mode 100644
index 0000000..aeb1d65
--- /dev/null
+++ b/src/hooks/useS3Preupload.tsx
@@ -0,0 +1,48 @@
+import { useState, useCallback, useMemo } from 'react';
+import { get } from '../requests';
+import axios from 'axios';
+
+
+export default () => {
+ const [url, setUrl] = useState<string>();
+ const [file, setFile] = useState<File>();
+ const [progress, setProgress] = useState<number>(0);
+
+ const isReady = useMemo(() => Boolean(file || url), [file, url]);
+
+
+ console.log({ file, url })
+
+ const setValue = useCallback((value: File | string | undefined): void => {
+ if (value instanceof File) {
+ setFile(value);
+ setUrl(undefined);
+ } else {
+ setUrl(value);
+ setFile(undefined);
+ }
+ }, [setUrl, setFile]);
+
+ const handleUploadProgress = useCallback((progressEvent: any) => {
+ setProgress(Math.round((progressEvent.loaded * 100) / progressEvent.total));
+ }, [setProgress]);
+
+ const resolve = useCallback(async (): Promise<string> => {
+ if (file) {
+ const config = {
+ headers: { 'Content-Type': 'image/png' },
+ onUploadProgress: handleUploadProgress
+ };
+
+ return get('/files')
+ .then(response => response.data)
+ .then(uploadUrl => axios.put(uploadUrl, file, config))
+ .then(response => {
+ const { config: { url } } = response;
+ return url ? url.slice(0, url.indexOf('?')) : '';
+ });
+ } else return url || '';
+ }, [file, handleUploadProgress, url]);
+
+ return { setValue, isReady, resolve, progress };
+};