Hi I'm making a ReactJS project and I'm trying to modify a function to make it more readable... It have a lot of API calls so it have a lot of .then() .catch() blocks. Do you have some suggestion to avoid all of this .then() .catch() blocks?? Because now is really unreadable.
const saveImgAvatar = (img_input) => {
setLoadingUploadImg(true)
//Salvo su aws e creo il cdn
let file = img_input
// Split the filename to get the name and type
let fileParts = img_input.name.split('.');
let fileName = context.currentUser.uid + "-img-avatar";
let fileType = fileParts[1];
console.log("file name" + fileName)
console.log("file parts" + fileType)
axios.post(process.env.REACT_APP_API_URL, {
fileName: fileName,
fileType: fileType
})
.then(response => {
var returnData = response.data.data.returnData;
var signedRequest = returnData.signedRequest;
var url = returnData.url;
//Ora salvo l'url
console.log("Recieved a signed request " + signedRequest);
// Put the fileType in the headers for the upload
var options = {
headers: {
'Content-Type': fileType
}
};
axios.put(signedRequest, file, options)
.then(result => {
setTalentImgAvatar(url)
//setCurrentImgAvatar(returnData.url)
//Salvo sul db
axios.put(process.env.REACT_APP_API_URL, { img_url: url })
.then(res => {
setLoadingUploadImg(false)
toggleShowEditImg(!showEditImg)
setAlertProfConf(true)
setTimeout(() => {
setAlertProfConf(false)
}, 1000)
})
.catch(function (error) {
console.log(error)
notifyMessage("error", "Errore nell'aggiornamento immagine")
setLoadingUploadImg(false)
})
})
.catch(error => {
//Apro un messaggio di errore
notifyMessage("error", "Errore")
//Notificato l'errore fermo lo spinner di loading
setLoadingUploadImg(false)
})
})
.catch(error => {
console.log(JSON.stringify(error));
//Apro un messaggio di errore
notifyMessage("error", "Errore")
//Notificato l'errore fermo lo spinner di loading
setLoadingUploadImg(false)
})
}