Apex – How to Process Papa Parse Results in Apex Class

apexcsvlightning-web-componentsparserparsing

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:

public static void processData(List<Map<String, Object>> csvData) { 

Or, if the CSV conforms to a type of wrapper object:

public static void processData(List<wrapper> csvData) {

Or, with some extra massaging, you can even pass in records:

RecordInsertLanes({
    csvData: results.data.map(data => ({ sobjectType: 'Account', ...data }),
})

...

public static void processData(Account[] csvData) {

Realistically, the options are pretty much unlimited, you just need to make the data agree on each end.

Related Topic