I know there is already a lot of discussion about this topic but I still haven't found an solution. I've found quite some answers saying that it is not quite possible so I am looking for an alternative on how to handle this correctly.
For the context I am using Vue with Pinia store and Axios for my API calls. In the backend we have a so called "lock system" which makes sure that only one person at a time can edit a certain object in the database.
The problem I have now is that I want to execute a method from my Pinia store with an axios API call IF the user closes the window/browser. It is an important API call which makes sure to delete any possible locks so other users can work on the object. The timeout for the lock is set to 2 hours so for example if the user is editing something and suddenly closes the window the object stays locked for another 2 hours.
We do have the option for other users to force the lock and kick the other user out of editing the object, but that is meant only for rare cases and I would ideally like to avoid it in this situation.
I have tried stuff along the lines:
window.addEventListener('beforeunload', function (e) {
e.preventDefault()
e.returnValue = ''
store.deleteLocks()
})
document.addEventListener('visibilitychange', function () {
if (document.visibilityState == 'hidden') {
store.deleteLocks()
}
})
I guess the closest I got was probably the following:
window.addEventListener('unload', function () {
store.deleteLocks()
})
But since its an async function its not getting run correctly.
So noting works quite as expected. Anyone has any idea how to smartly handle this or work around it?