diff options
author | eug-vs <eug-vs@keemail.me> | 2020-08-14 01:25:56 +0300 |
---|---|---|
committer | eug-vs <eug-vs@keemail.me> | 2020-08-14 01:25:56 +0300 |
commit | 60583c1496aeaf366087bff550da8e9288ff33cf (patch) | |
tree | ef3700567800ec128db978be326ae178d2197e35 /src/hooks | |
parent | d7aba191cdfbf6f2f5e35bcaa94e011fafcde3dc (diff) | |
download | which-ui-60583c1496aeaf366087bff550da8e9288ff33cf.tar.gz |
refactor: add useS3Preupload hook
Diffstat (limited to 'src/hooks')
-rw-r--r-- | src/hooks/useS3Preupload.tsx | 48 |
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 }; +}; |