I'm trying to make an api request, to my server where i have some files, that I'm sending along.
I have made an array of custom objects, where i have two parameters, the file extension and the raw data base654 encoded
onSubmitHandler = (e) =>{
e.preventDefault()
const contactRequest = {
email: this.state.email,
name: this.state.name,
message: this.state.message,
files: this.state.files,
result: this.state.files.map(file => ({
"file": this.findFileTypeHandler(file.name),
"data": this.getBase64(file)
}))
}
console.log(this.getBase64(this.state.files[0]))
console.log(contactRequest)
}
the issue is in my getBase64 function
i havde tried several approaches.
getBase64 = file => {
let ans = ''
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result) //logged correctly here, but after undefined is returned
ans = reader.result
};
reader.onerror = function (error) {
console.log('error is ', error)
return error;
};
return ans;
}
the correct answer is logged correctly, but it returns undefined first. This is due to It's asynchronous behavior.
Is there a way, so i can make it wait till the function is loaded correctly.
I initially though about making a async await approach, but i think this would get messy, since I'm already planing, to use promises, when i make a post request to my server.