0% found this document useful (0 votes)
3 views

csv uploader component

The document describes a React component called CsvUploader that allows users to upload CSV files and parse their contents using the Papa Parse library. It initializes a Firebase app and uploads the parsed data to a Firestore collection, handling both file selection and data preview. The component ensures required fields are present and formats the data appropriately before uploading it in a single transaction.

Uploaded by

Dylan Chaos
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

csv uploader component

The document describes a React component called CsvUploader that allows users to upload CSV files and parse their contents using the Papa Parse library. It initializes a Firebase app and uploads the parsed data to a Firestore collection, handling both file selection and data preview. The component ensures required fields are present and formats the data appropriately before uploading it in a single transaction.

Uploaded by

Dylan Chaos
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

import React, { useState } from "react";

import Papa from "papaparse";


import firebase from "firebase/app";
import "firebase/firestore";
import PropTypes from "prop-types";
import searchByNameArrayConstructor from "./searchByNameArray";

const REQUIRED_FIELDS = {
estado: "",
municipio: "",
programa: "",
tipoDeApoyo: "",
comentarios: "",
fechaReporte: "",
prioridadReporte: "",
rangoEdad: "",
nombre: "",
apellidoPaterno: "",
apellidoMaterno: "",
genero: "",
fechaNacimiento: "",
calle: "",
numeroExterior: "",
numeroInterior: "",
colonia: "",
codigoPostal: "",
telefono: "",
celular: "",
correo: "",
whatsapp: "",
principalProblema: "",
calificacionServicio: "",
ine: "",
curp: "",
distritoFederal: "",
distritoLocal: "",
seccionElectoral: "",
origen: "",
funcionarioRecepcion: "",
estatus: "",
folio: "",
photo: "",
photo2: "",
geolocalizacion: "",
};

const CsvUploader = ({ firebaseConfig }) => {


const [csvData, setCsvData] = useState([]);
const [fileName, setFileName] = useState("");

if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}

const handleFileChange = (event) => {


const file = event.target.files[0];
setFileName(file?.name || "");

if (file) {
Papa.parse(file, {
header: true,
skipEmptyLines: true,
complete: (results) => {
const formattedData = results.data.map((row) => {
const searchByNameArray = searchByNameArrayConstructor(row)
const formattedRow = {
...REQUIRED_FIELDS,
...row,
searchByNameArray,
};
if (!formattedRow.notas || formattedRow.notas.trim() === "") {
formattedRow.notas = [{}];
} else {
formattedRow.notas = formattedRow.notas.split(",").map((nota) =>
nota.trim());
}
return formattedRow;
});
setCsvData(formattedData);
},
error: (error) => {
console.error("Error parsing CSV file:", error);
},
});
}
};

const handleUploadToFirebase = async () => {


if (csvData.length === 0) {
alert("No data to upload. Please select a valid CSV file.");
return;
}

const dbRef = firebase.firestore().collection("Reports");

try {
await firebase.firestore().runTransaction(async (transaction) => {
csvData.forEach((row) => {
const docId = row.id?.trim() ? row.id : undefined;
if (docId) {
transaction.set(dbRef.doc(docId), row);
} else {
transaction.set(dbRef.doc(), row);
}
});
});

alert("Data successfully uploaded to Firebase in a single transaction!");


} catch (error) {
console.error("Error uploading data to Firebase:", error);
}
};

return (
<div style={{ padding: "20px", fontFamily: "Arial, sans-serif" }}>
<h1>CSV File Uploader</h1>

<div style={{ marginBottom: "20px" }}>


<input
type="file"
accept=".csv"
onChange={handleFileChange}
style={{ marginBottom: "10px" }}
/>
{fileName && <p>Selected File: {fileName}</p>}
</div>

{csvData.length > 0 && (


<div style={{ marginBottom: "20px" }}>
<h2>Firebase Data Preview</h2>
{csvData.map((row, index) => (
<div key={index} style={{ marginBottom: "20px" }}>
<h3>Document {row.id || "(generated)"}</h3>
<table
border="1"
style={{ width: "100%", borderCollapse: "collapse" }}
>
<tbody>
{Object.entries(row).map(([key, value]) => (
<tr key={key}>
<td
style={{ padding: "8px", backgroundColor: "#f4f4f4" }}
>
{key}
</td>
<td style={{ padding: "8px" }}>
{JSON.stringify(value)}
</td>
</tr>
))}
</tbody>
</table>
</div>
))}
<button
onClick={handleUploadToFirebase}
style={{ padding: "10px 20px", cursor: "pointer" }}
>
Load to Firebase
</button>
</div>
)}
</div>
);
};

CsvUploader.propTypes = {
firebaseConfig: PropTypes.object.isRequired,
};

export default CsvUploader;

You might also like