I am building a helper for uploading files in react native, although I cannot get to fire xhr.onerror, I was hoping to throw an error inside onreadystatechange
by checking for the status and the onerror would fire but unfortunately it isn't. Any good approach how I can handle this?
Here is the whole code:
sendXHR = async (
url: string,
formData: FormData,
eventListeners: XMLHttpRequestEventTarget,
) => {
let xhr = new XMLHttpRequest();
xhr.open('POST', `${API_URL}${url}`, true);
const credentials: any = await retrieveToken();
xhr.setRequestHeader('Authorization', `Bearer ${credentials.password}`);
xhr.upload.onabort = eventListeners.onabort;
xhr.upload.onprogress = eventListeners.onprogress;
xhr.upload.onerror = eventListeners.onerror;
xhr.upload.onloadstart = eventListeners.onloadstart;
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
const status = xhr.status;
if (status < 200 || status >= 300) {
throw new Error(xhr.statusText);
}
}
};
xhr.send(formData);
return {
response: new Promise((resolve, reject) => {
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response);
} else {
reject({status: xhr.status, message: xhr.statusText});
}
};
xhr.onerror = () => {
reject({status: xhr.status, message: xhr.statusText});
};
}),
xhr,
};
};