0

I have a csv file that I want to convert and upload to my local json server I have tried this code using papaparse

const handleSubmit = () => {
    for (let i = 0; i < data.length; i++) {
      let exactData = data[i].data;

      let phone = exactData[0];
      let lastname = exactData[1];
      let firstname = exactData[2];
      let email = exactData[3];

      let CSVData = {
        phone: phone,
        lastname: lastname,
        firstname: firstname,
        email: email,
      };

      fetch("http://localhost:8000/subm", {
        method: "POST",
        headers: { "content-Type": "application/json" },
        body: JSON.stringify(CSVData),
      })
        .then((response) => response.json())
        .then((data) => {
          alert("new users added");
         
        });
    }
  };

Is there a better way of doing this?

zhulien
  • 5,145
  • 3
  • 22
  • 36
Haq
  • 35
  • 7
  • Many developers prefer axios over fetch. For more info checkout this [link](https://stackoverflow.com/questions/40844297/what-is-difference-between-axios-and-fetch) – Sifat Amin Jun 22 '21 at 02:33
  • If you are looking for how to parse csv data: [https://stackoverflow.com/questions/1293147/example-javascript-code-to-parse-csv-data](https://stackoverflow.com/questions/1293147/example-javascript-code-to-parse-csv-data) – Ricky Mo Jun 22 '21 at 02:44

1 Answers1

0

You can use destructuring to simplify the code

let exactData = ["12345678","Mouse","Mickey","abc@def.com"]
let [phone,lastname,firstname,email] = exactData;
let csvData = {phone,lastname,firstname,email};
console.log(csvData);
Ricky Mo
  • 6,285
  • 1
  • 14
  • 30