I am building a custom file upload component as follows. I prepare my list of uploaded files inside the function handleFilesUpload. I then call another function called handleSaveFiles but inside of this function the variable that holds the list of files is empty. Can someone point me to why that is please?
docs.html
<template>
<div class="slds-m-around_medkium">
<lightning-input type="file"
onchange={handleFilesUpload}
multiple>
</lightning-input>
</div>
<template if:true={showUpload}>
<section role="dialog" tabindex="-1" aria-modal="true" aria-labelledby="modal-heading-01">
<div>
<button onclick={closePopUp}>x</button>
<div>
<h1>Select File Type</h1>
</div>
<div>
<div>
<lightning-combobox name="File Type" label="File Type" value="" placeholder="Choose File Type" options={filetype}
onchange={handleChange}></lightning-combobox>
</div>
</div>
</div>
</section>
<div role="presentation"></div>
</template>
</template>
docs.js
import { LightningElement, api, track, wire } from 'lwc';
import getFiles from '@salesforce/apex/docsUpload.getFiles';
import saveFiles from '@salesforce/apex/docsUpload.saveFiles';
export default class docs extends LightningElement {
@api recordId
filesUploaded = [];
showUpload = false;
filetype = { id: 1, label: "Item 1" },
{ id: 2, label: "Item 2" },
{ id: 3, label: "Item 3" }
]
connectedCallback() {
this.loadFiles();
}
loadFiles() {
getFiles({appId: this.recordId})
.then(result => {
console.log(JSON.stringify(result));
})
.catch(error => {
console.log(JSON.stringify(error));
});
}
handleFilesUpload(event) {
let files = event.target.files;
let filescount = files.length;
let readOpearationCount = 0;
if(files.length > 0) {
let filesName = '';
for(let i = 0; i < files.length; i++) {
let file = files[i];
filesName = filesName + file.name + ',';
let freader = new FileReader();
freader.onload = () => {
var fileContents = freader.result.split(',')[1]
this.filesUploaded.push({'fileName':file.name, 'fileContent':fileContents});
};
freader.onloadend = () => {
readOpearationCount++;
if(readOpearationCount == filescount) {
this.showUpload = true;
this.handleSaveFiles();
}
};
freader.readAsDataURL(file);
}
}
}
handleSaveFiles() {
console.log(JSON.stringify(this.filesUploaded));
saveFiles({
recordId: this.recordId,
fileData: JSON.stringify(this.filesUploaded)
})
.then(result => {
if(result){
this.filesUploaded = [];
console.log('file uploaded successfully.');
}
else {
console.log('error during file upload');
}
}).catch(error => {
console.log('error');
});
}
}