this is the image upload code the URL only returns after the form has been submitted to the backend. Trying send upload image to an image server on button click, then return URL and store to the backend. How to do it sequentially
const handleImgUpload = async imgb => {
try {
const images = imgb;
let promiseArray = [];
let imgbb = images.toString('base64');
const details = {image: `${imgbb}`};
let formBody = [];
for (const property in details) {
const encodedKey = encodeURIComponent(property);
const encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + '=' + encodedValue);
}
formBody = formBody.join('&');
promiseArray.push(
fetch(
'https://api.imgbb.com/1/upload?key=xxxxxxxxxxxx',
{
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
},
body: formBody,
},
).then(r => r.json()),
);
Promise.all(promiseArray)
.then(values => {
if (values[0].success) {
let thumb = '';
values.map(imgs => {
thumb = values[0].data.thumb.url;
setImgUrl(imgs.data.url.replace(/["']/g, ''));
});
// setImageLoader(false);
//YOU SEND imgURL
// handleSubmitButton();
} else {
// setImageLoader(false);
alert(
'An error occurred while uploading image, please check your connection and try again',
);
}
})
.catch(err => {
// setImageLoader(false);
console.log('ERORRRRR', err);
alert(err);
});
} catch (e) {
// setImageLoader(false);
console.log('ERRRR', e);
}
};
this is the submit button code
I want to fetch the return URL first and then store it to a state then upload it to backend**
const handleSubmitButton = async () => {
handleImgUpload(img); **handle upload function**
// Show Loader
setLoading(true);
UserApi.ElectionReport({
imgUrl,
})
.then(function (response) {
// response handling
setValue(response);
console.log('res', response.data);
if (response.data == 'successful') {
// console.log('res', response.data)
navigation.navigate('Home');
alert('Sent Successfully');
return;
}
setLoading(false);
console.log('res', response.data);
})
.catch(function (error) {
// error handling
if (error.response) {
alert(error.message);
setLoading(false);
}
});
};