I can't use sendBeacon as I need to send Bearer token and it seems that the only header you can send with sendBeacon is content type.
I have a user who has a presence which is either "AVAILABLE", "IN CALL" or "DO NOT DISTURB". My problem is that right now, if the user is "IN CALL" and then they exit the browser or close the tab, their presence doesn't change from "IN CALL" to the default "AVAILABLE". Then if they load the website again, their status is still "IN CALL" even if they aren't in a call anymore.
This is why I decided to add a beforeunload event listener in the componentDidMount() that makes a POST request to the back-end in order to change the presence to the default "AVAILABLE". My first problem was that most of the time, the POST request wouldn't get through. I assume the request didn't go through because it was racing with the closing browser, and losing.
My question is how can I make it 100% sure that the POST request will get through before the browser/tab closes?
Currently I'm working with this:
componentDidMount() {
window.addEventListener('beforeunload', this.onBeforeUnload);
}
And:
onBeforeUnload = (event) => {
try {
const headers = {
Authorization: `Bearer ${getAccessToken()}`,
'Content-Type': 'application/json',
};
const defaultPresence = {
presence: 'AVAILABLE',
message: '',
};
const url = getServerURL() + urls.PRESENCE;
fetch(
url,
{
method: 'POST',
headers,
body: JSON.stringify(defaultPresence),
},
);
} catch (error) {
console.log(error);
}
}