import { DataSource, Entity, EntityCollection, useDataSource, useTranslation } from "@firecms/core"; import { Button, CenteredView, CircularProgress, Typography, } from "@firecms/ui"; import { useEffect, useRef, useState } from "react"; import { ImportConfig } from "../types"; export function ImportSaveInProgress ({ path, pathSegments, importConfig, collection, onImportSuccess }: { path: string, /** `path` split at its real segment boundaries, when known. Never derived from `path`. */ pathSegments?: string[], importConfig: ImportConfig, collection: C, onImportSuccess: (collection: C) => void }) { const { t } = useTranslation(); const [errorSaving, setErrorSaving] = useState(undefined); const dataSource = useDataSource(); const savingRef = useRef(false); const [processedEntities, setProcessedEntities] = useState(0); function save() { if (savingRef.current) return; savingRef.current = true; saveDataBatch( dataSource, collection, path, pathSegments, importConfig.entities, 0, 25, setProcessedEntities ).then(() => { onImportSuccess(collection); savingRef.current = false; }).catch((e) => { setErrorSaving(e); savingRef.current = false; }); } useEffect(() => { save(); }, []); if (errorSaving) { return ( {t("error_saving_data")} {errorSaving.message} ); } return (
{t("saving_data")} {processedEntities}/{importConfig.entities.length} {t("entities_saved")} {t("do_not_close_tab")}
); } function saveDataBatch(dataSource: DataSource, collection: EntityCollection, path: string, pathSegments: string[] | undefined, data: Partial>[], offset = 0, batchSize = 25, onProgressUpdate: (progress: number) => void): Promise { console.debug("Saving imported data", offset, batchSize); const batch = data.slice(offset, offset + batchSize); return Promise.all(batch.map(d => dataSource.saveEntity({ path, pathSegments, values: d.values, entityId: d.id, collection, status: "new" }))) .then(() => { if (offset + batchSize < data.length) { onProgressUpdate(offset + batchSize); return saveDataBatch(dataSource, collection, path, pathSegments, data, offset + batchSize, batchSize, onProgressUpdate); } onProgressUpdate(data.length); return Promise.resolve(); }); }