Folks,
I want to parse CSV files with papa parse in apex. I have a lwc to upload the file and a custom apex class to massage the data and insert results to custom object. My question is what do I pass to my apex class for my csvData parameter? A string array? Array of objects? I can't figure it out.
Here is the method that sends the data to my apex class from my lwc:
onchange(event) {
[...event.target.files].forEach(file => {
Papa.parse(file, {
header: true,
complete: (results) => {
this._rows = results.data;
this.loading = false;
console.log(results.data);
RecordInsertLanes({
csvData: results.data,
})
.then(result => {
console.log(result);
})
.catch((error) => {
});
},
error: (error) => {
console.error(error);
this.loading = false;
}
});
})
}
And this is my apex class:
public with sharing class csvUploadHandler {
@AuraEnabled
//what am i suppose to pass here for csvData? array of strings? Array of sObject?
public static void processData(String[] csvData){
for(String ln : csvData){
System.debug(ln);
}
}
}
Best Answer
From your current code, Apex will be expecting a named object array, or, more formally, a List of Map objects with a String key and an Object value:
Or, if the CSV conforms to a type of wrapper object:
Or, with some extra massaging, you can even pass in records:
...
Realistically, the options are pretty much unlimited, you just need to make the data agree on each end.