Skip to content

Commit

Permalink
♻️ Extract an async func to read upload file
Browse files Browse the repository at this point in the history
  • Loading branch information
doitian committed Feb 27, 2024
1 parent ffa3f10 commit 0954be3
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 25 deletions.
31 changes: 6 additions & 25 deletions src/ImportAddressPage.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Alert, Button, FileInput } from "flowbite-react";
import { useState } from "react";
import { importMultisigAddresses } from "./lib/multisig-address.js";
import { readAsText } from "./lib/file-upload.js";

const ERROR_MESSAGE = "Opps, error occurs when processing the uploaded file";

Expand All @@ -10,36 +11,16 @@ export default function NewAddressPage({ addAddress, navigate }) {
error: null,
});

const submit = (e) => {
const submit = async (e) => {
e.preventDefault();
setState({ isProcessing: true, error: null });

try {
const reader = new FileReader();

reader.addEventListener("load", (loaded) => {
try {
const addresses = importMultisigAddresses(
JSON.parse(loaded.target.result),
);
addAddress(addresses);
navigate("#/");
} catch (error) {
setState({
isProcessing: false,
error: `${ERROR_MESSAGE}: ${error}`,
});
}
});
reader.addEventListener("error", () => {
setState({ isProcessing: false, error: ERROR_MESSAGE });
});
reader.addEventListener("abort", () => {
setState({ isProcessing: false, error: "Uploading aborted" });
});

const fileInput = document.getElementById("file-upload");
reader.readAsText(fileInput.files[0]);
const fileContent = await readAsText(fileInput.files[0]);
const addresses = importMultisigAddresses(JSON.parse(fileContent));
addAddress(addresses);
navigate("#/");
} catch (error) {
setState({
isProcessing: false,
Expand Down
13 changes: 13 additions & 0 deletions src/lib/file-upload.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export function readAsText(file) {
const reader = new FileReader();

return new Promise((resolve, reject) => {
reader.addEventListener("load", (loaded) => {
resolve(loaded.target.result);
});
reader.addEventListener("error", reject);
reader.addEventListener("abort", reject);

reader.readAsText(file);
});
}

0 comments on commit 0954be3

Please sign in to comment.