benwinding / react-admin-import-csv

A csv file import button for react-admin
https://benwinding.github.io/react-admin-import-csv
MIT License
135 stars 47 forks source link

Question: Add additional field to CSV records before posting #58

Closed irborrero closed 3 years ago

irborrero commented 3 years ago

Hello,

First of all, thank you for this feature! It really saves a lot of time.

Here is my use case:

I am importing a csv file that looks like this:

title, id
 title1, 1
 title2, 2

I would like to add an extra CSV field before posting, so that the post request payload looks like this:

{
   title: title1,
   id: 1,
   company: 1,
},
{
  title: title2,
  id: 2, 
  company: 1,
},

The additional field is always a constant value that I need to send to my API endpoint to perform the post request.

Is it possible to achieve this with transform rows in config? Has anyone tried to do this before?

benwinding commented 3 years ago

Hi @irborrero,

That's correct, you can use the transformRows callback in the options, which returns a Promise containing the transformed rows. Yours might look like:

const options = {
  transformRows: (csvRows) => {
    const newRows = []; // new rows here!
    return newRows;
  }
}

You could also modify your Dataprovider to handle this too. Let me know how you go :) Ben

irborrero commented 3 years ago

Hi @benwinding

Yes it worked!

Did this:

const config: ImportConfig = {
  transformRows: (csvRows: any[]) => {
    const transformedCsvRows = [];
    csvRows.map((row) => {
      row.companyId = companyId;
      transformedCsvRows.push(row);
    });
    return transformedCsvRows;
  },
};

Thanks :)