0% found this document useful (0 votes)
7 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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 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
We take content rights seriously. If you suspect this is your content, claim it here.
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

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy