Chore: Resolves TS errors related to FileReader/ImageUploader (#965)

* Resolves TS errors related to FileReader/ImageUploader

* Also tackle cropImage errors

Co-authored-by: Bailey Pumfleet <[email protected]>
This commit is contained in:
Alex van AndelandBailey Pumfleet authored and GitHub committed 2021-10-16 10:42:28 +00:00
1 parent a67813ee77
commit 22c4d29db5
4 files changed
+44 -34

No files matched your search

+3 -2
View File
@@ -7,7 +7,7 @@ export type Area = {
y: number;
};
const createImage = (url) =>
const createImage = (url: string) =>
new Promise<HTMLImageElement>((resolve, reject) => {
const image = new Image();
image.addEventListener("load", () => resolve(image));
@@ -16,10 +16,11 @@ const createImage = (url) =>
image.src = url;
});
export async function getCroppedImg(imageSrc: string, pixelCrop: Area) {
export async function getCroppedImg(imageSrc: string, pixelCrop: Area): Promise<string> {
const image = await createImage(imageSrc);
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
if (!ctx) throw new Error("Context is null, this should never happen.");
const maxSize = Math.max(image.naturalWidth, image.naturalHeight);
const resizeRatio = MAX_IMAGE_SIZE / maxSize < 1 ? Math.max(MAX_IMAGE_SIZE / maxSize, 0.75) : 1;
+7 -12
View File
@@ -11,7 +11,7 @@ export const useFileReader = (options: UseFileReaderProps) => {
const { method = "readAsText", onLoad } = options;
const [file, setFile] = useState<File | null>(null);
const [loading, setLoading] = useState<boolean>(false);
const [error, setError] = useState<ProgressEvent<FileReader> | null>(null);
const [error, setError] = useState<DOMException | null>(null);
const [result, setResult] = useState<string | ArrayBuffer | null>(null);
useEffect(() => {
@@ -28,21 +28,16 @@ export const useFileReader = (options: UseFileReaderProps) => {
const reader = new FileReader();
reader.onloadstart = () => setLoading(true);
reader.onloadend = () => setLoading(false);
reader.onerror = setError;
reader.onerror = () => setError(reader.error);
reader.onload = (e) => {
setResult(e.target.result);
reader.onload = (e: ProgressEvent<FileReader>) => {
setResult(e.target?.result ?? null);
if (onLoad) {
onLoad(e.target.result);
onLoad(e.target?.result ?? null);
}
};
try {
reader[method](file);
} catch (e) {
setError(e);
}
reader[method](file);
}, [file, method, onLoad]);
return [{ result, error, file, loading }, setFile];
return [{ result, error, file, loading }, setFile] as const;
};