2021-10-02 11:04:47 +00:00
|
|
|
import { useEffect, useState } from "react";
|
|
|
|
|
|
|
|
type ReadAsMethod = "readAsText" | "readAsDataURL" | "readAsArrayBuffer" | "readAsBinaryString";
|
|
|
|
|
|
|
|
type UseFileReaderProps = {
|
|
|
|
method: ReadAsMethod;
|
|
|
|
onLoad?: (result: unknown) => void;
|
|
|
|
};
|
|
|
|
|
|
|
|
export const useFileReader = (options: UseFileReaderProps) => {
|
|
|
|
const { method = "readAsText", onLoad } = options;
|
|
|
|
const [file, setFile] = useState<File | null>(null);
|
|
|
|
const [loading, setLoading] = useState<boolean>(false);
|
2021-10-16 10:42:28 +00:00
|
|
|
const [error, setError] = useState<DOMException | null>(null);
|
2021-10-02 11:04:47 +00:00
|
|
|
const [result, setResult] = useState<string | ArrayBuffer | null>(null);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (!file && result) {
|
|
|
|
setResult(null);
|
|
|
|
}
|
|
|
|
}, [file, result]);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (!file) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const reader = new FileReader();
|
|
|
|
reader.onloadstart = () => setLoading(true);
|
|
|
|
reader.onloadend = () => setLoading(false);
|
2021-10-16 10:42:28 +00:00
|
|
|
reader.onerror = () => setError(reader.error);
|
2021-10-02 11:04:47 +00:00
|
|
|
|
2021-10-16 10:42:28 +00:00
|
|
|
reader.onload = (e: ProgressEvent<FileReader>) => {
|
|
|
|
setResult(e.target?.result ?? null);
|
2021-10-02 11:04:47 +00:00
|
|
|
if (onLoad) {
|
2021-10-16 10:42:28 +00:00
|
|
|
onLoad(e.target?.result ?? null);
|
2021-10-02 11:04:47 +00:00
|
|
|
}
|
|
|
|
};
|
2021-10-16 10:42:28 +00:00
|
|
|
reader[method](file);
|
2021-10-02 11:04:47 +00:00
|
|
|
}, [file, method, onLoad]);
|
|
|
|
|
2021-10-16 10:42:28 +00:00
|
|
|
return [{ result, error, file, loading }, setFile] as const;
|
2021-10-02 11:04:47 +00:00
|
|
|
};
|