From 60583c1496aeaf366087bff550da8e9288ff33cf Mon Sep 17 00:00:00 2001
From: eug-vs <eug-vs@keemail.me>
Date: Fri, 14 Aug 2020 01:25:56 +0300
Subject: refactor: add useS3Preupload hook

---
 src/hooks/useS3Preupload.tsx | 48 ++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 48 insertions(+)
 create mode 100644 src/hooks/useS3Preupload.tsx

(limited to 'src/hooks/useS3Preupload.tsx')

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 };
+};
-- 
cgit v1.2.3

