0

I'm getting this error from a component which is a file upload component. Unfortunately, it's not even producing debug logs, so troubleshooting is quite difficult. This is the error :

Cannot read property 'trim' of undefined

and this is the other description that comes with it :

Object.CSV2JSON()@https://mydomain.lightning.force.com/lightning/r/Program__c/a6S2J000000CuHOUA0/components/c/programFileUploadProcess.js:181:39
FileReader.reader.onload()@https://mydomain.lightning.force.com/lightning/r/Program__c/a6S2J000000CuHOUA0/components/c/programFileUploadProcess.js:72:33

The only thing I have to go on are the lines : 181:39 ; and 72:33. But unfortunately, I don't know which lines those are referring to. I wish I could provide more information. But I won't even produce debug logs.

Here is the Controller of the component :

({
    doInit : function(component, event, helper){
        // get the current record id
        var recId = component.get("v.recordId");
        var objType = component.get("v.sObjectName");
        //set the recordId to attribute
        component.set("v.programID", recId);
        
       
        
    },
    setUpload :function(component, event, helper) {
        

        var fileInput = component.find("file").getElement();
        //alert(fileInput.files[0].type);
        //if(fileInput.files[0].type === 'application/vnd.ms-excel'){
            console.log('ONclickLength : '+ fileInput.length);
            var file = fileInput.files[0];
            var toastEvent = $A.get("e.force:showToast");
                        toastEvent.setParams({
                        title: 'Success !!',
                        message: 'File Selected Successfully !!',
                        key: 'info_alt',
                        duration : '5000',
                        type: 'success',
                        mode: 'pester'
            });
            toastEvent.fire();
            component.set("v.disableUpload",'false');
        //}
        // else{
        //     component.set("v.disableUpload",'true');
        //     component.find("file").getElement().value = '';
        //     var toastEvent = $A.get("e.force:showToast");
        //                 toastEvent.setParams({
        //                 title: 'Warning  - Invalid File  !!',
        //                 message: 'Please Select Only A Excel File !!',
        //                 key: 'info_alt',
        //                 duration : '5000',
        //                 type: 'warning',
        //                 mode: 'pester'
        //     });
        //     toastEvent.fire();
        // }
        
        
    },
    
    readFile: function (component, event, helper) {
        
        component.set("v.showSpinner", true);
        
        var fileInput = component.find("file").getElement();
        var file = fileInput.files[0];
        
        if (file) {
        //console.log("File");
        var reader = new FileReader();
        reader.readAsText(file, "UTF-8");
        reader.onload = function (evt) {
            //console.log("EVT FN");
            var csv = evt.target.result;
            //console.log('@@@ csv file contains'+ csv);
            var result = helper.CSV2JSON(component,csv);
            //alert('HOLD');
            //console.log('@@@ result = ' + result);
            //console.log('@@@ Result = '+JSON.parse(result));
            helper.passJSONToApex(component,result);
           
            
        }
        reader.onerror = function (evt) {
            //console.log("error reading file");
        }
    }

    },
   
})

and here is the Helper :

({
        CSV2JSON: function (component,csv) {
            //console.log('@@@ Incoming csv = ' + csv);
                
                //var array = [];
                var arr = []; 
                
                arr =  csv.split('\n');
                //console.log('@@@ Array  = '+array);
                console.log('@@@ arr = '+arr);
                //arr.pop();
                var jsonObj = [];
                var headers = arr[0].replace(/ /g,'_').replace('/','_').split(',');
                console.log(headers);
                for(var i = 1; i < arr.length; i++) {
    
                    console.log('Not Split : arr : '+i+ ': '+arr[i] );
    
                    var data = arr[i].split(',');
                    console.log('Split DAta : '+i+ ': '+data );
                    var obj = {};
                    
                    var x=0;
                    var dataIndex=0;
    
                    var finalValue=[];
                    var finalIndex=0;
                    for(var j = 0; j < data.length; j++) {
                        
                        var h;
                        var d;
                        var str;
                        console.log(headers[j]+' : '+ data[j]);
                        if(data[j].indexOf('"') !== 0){
                            finalValue[finalIndex]=data[j];
                            finalIndex++;
                        }
                        if(data[j].indexOf('"') == 0){
                                //console.log('J : '+j);
                                //console.log('x : '+x);
                                if(j >= x || x===0){
                                    x=j;
                                
                                if(data[x] !== undefined){
                                    str = data[x].replace('"','');
                                
                                }
                                x++;
                                
                                while(data[x] !== undefined && data[x].includes('"') === false){
                                    str = str + data[x];
                                    x++;
                                }
                                
                            
                                if(data[x] !== undefined && data[x].includes('"')){
                                    str =str + data[x].replace('"','');
                                    
                                    
                                }
                                console.log('Str : ' +str);
                            finalValue[finalIndex]=str;
    
                            finalIndex++;
                            }
                            dataIndex++;
                            //console.log('FOrIndex  : ' +dataIndex);
                            //
                            
                            j=x;
                            
    
                        }
                        //obj[headers[j].trim()] = data[j].trim();
                       
                        //Remove coment from here 
    
                        
    
                        //console.log('@@@ obj headers = ' + obj[headers[j].trim()]);
                        //till here
                    }
                    for(var j=0;j<headers.length;j++){
                        //if(headers[j].length > 0){
                            console.log(headers[j]+ ' :-  '+finalValue[j]);
                        if(headers[j] != undefined){
                            h=headers[j].trim();
                        }
                        else
                        {
                        h=headers[j];
                        }
                        
                        if(data[j] != undefined){
                        d = finalValue[j].trim();
                        }
                        else{
                        d = finalValue[j];
                        }
                        
                        obj[h] = d;
                        //}
                        
    
                    }
                    
                    jsonObj.push(obj);
                }
                //alert('wait');
                var json = JSON.stringify(jsonObj);
                console.log('@@@ json = '+ json);
                return json;
        
                
            },
    
        passJSONToApex : function (component,jsonstr){
            var recId = component.get("v.recordId");
            
            console.log('passJSONToApex');
            if(jsonstr){ 
                
                var action = component.get("c.createNewRecords");
                console.log('jsonData : '+ jsonstr );
                action.setParams({
                        "jsonData" : jsonstr,
                        "programId" : recId
                    });
                action.setCallback(this, function(response) {
                    var state = response.getState();
                    if (state === "SUCCESS") {  
                        component.set("v.Spinner", false); 
                        var colorCode = response.getReturnValue();
                        if(colorCode === 'GREEN'){
                            var toastEvent = $A.get("e.force:showToast");
                            toastEvent.setParams({
                            title: 'Insertion Successful !!',
                            message: 'Records Created Successfully - Navigating to Program Record.',
                            key: 'info_alt',
                            duration : '5000',
                            type: 'success',
                            mode: 'pester'
                        });
                        toastEvent.fire();
    
                        }
                        if(colorCode === 'RED'){
                            var toastEvent = $A.get("e.force:showToast");
                            toastEvent.setParams({
                            title: 'Insertion Failed !!',
                            message: 'Records Insertion Failed - Navigating to Program Record.',
                            key: 'info_alt',
                            duration : '5000',
                            type: 'error',
                            mode: 'pester'
                        });
                        toastEvent.fire();
    
                        }
                        if(colorCode === 'YELLOW'){
                            var toastEvent = $A.get("e.force:showToast");
                            toastEvent.setParams({
                            title: 'Partially Inserted  !!',
                            message: 'Few Records Created Successfully - Navigating to Program Record.',
                            key: 'info_alt',
                            type: 'warning',
                            duration : '5000',
                            mode: 'pester'
                        });
                        toastEvent.fire();
    
                        }
                        
                        if(colorCode === 'Batch'){
                            var toastEvent = $A.get("e.force:showToast");
                            toastEvent.setParams({
                            title: 'Upload in Process',
                            message: 'Spend data upload has been started. You will receive an email notification once it is done.',
                            key: 'info_alt',
                            duration : '50000',
                            **type: 'success',**
                            mode: 'pester'
                        });
                        toastEvent.fire();
    
                        }
                        
                        if(colorCode === 'Unknown'){
                            var toastEvent = $A.get("e.force:showToast");
                            toastEvent.setParams({
                            title: 'Insertion Failed !!',
                            message: 'Invalid Data : Insertion Failed..No Records Inserted',
                            key: 'info_alt',
                            duration : '5000',
                            type: 'error',
                            mode: 'pester'
                        });
                        toastEvent.fire();
    
                        }
                        
                         
                        
                        
                        window.open('/'+recId,'_self');
    
                          
                    //window.open('/'+recId,'_self');        
                    }
                    else if (state === "ERROR") {
                        var errors = response.getError();
    
                        var toastEvent = $A.get("e.force:showToast");
                            toastEvent.setParams({
                            title: 'Error Occured !!' + errors[0].message,
                            message: 'No Records Created',
                            key: 'info_alt',
                            type: 'error',
                            mode: 'pester'
                        });
                        toastEvent.fire();
    
                        if (errors) {
                            if (errors[0] && errors[0].message) {
                                console.log("Error message: " + 
                                        errors[0].message);
                            }
                        } else {
                           console.log("Unknown error");
                            
                        }
                        window.open('/'+recId,'_self');
                    }
                }); 
                
                $A.enqueueAction(action);    
                
            }
        },
        
            
    })

I wish I could provide more information, but like I said I can't even produce debug logs.

I can say that line 181 in the Helper is : "type: 'success'," - but I'm not even sure that is what is being referenced in the error. My Javascript skills are very limited.

Any help I can get would be greatly appreciated.

1

You should probably be checking

if(finalValue[j]!=undefined)

instead of

if(data[j] != undefined)
| improve this answer | |
  • Would you do that for every place if(data[j] is used throughout the code, or just in particular uses of it ? @user6670 – Zoom_v Sep 2 at 13:33
  • @zoom_v it will be only at one place where you are trimming finalValue[j] but you are checking undefined on data[j],since the issue is you are using trim function on finalValue[j] which probably is undefined in some case – User6670 Sep 2 at 13:43
  • Should I just change each occurrence of if(data..) individually and test until it actually works ? @user6670 – Zoom_v Sep 2 at 13:54
  • @Zoom_v no just change if(data[j] != undefined) in your helper with if(finalValue[j]!=undefined) – User6670 Sep 2 at 13:56
  • 1
    @Zoom_v you used wrong variable in undefined check, if that field data is inside that variable then it could be because of that field and yeah it is not related to data size – User6670 Sep 2 at 15:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.