Reputation: 179
I need to remove cookies from the browser when the user exits the application if a certain cookie is present(using universal-cookie).
the code I have:
componentWillUnmount(){
const cookies = new Cookies();
if(cookies.get("remember")==0){
cookies.remove("userName");
cookies.remove("password")
}
}
works on other components but I need it on the root only to fire before the user closes the app.
Why wont componentWillUnmount fire when the application exits?
Upvotes: 1
Views: 2319
Reputation: 222503
componentWillUnmount
isn't supposed to be called when browser window is closed. beforeunload
event allows to perform synchronous actions:
componentDidMount() {
window.addEventListener('beforeunload', this.onUnmount, false);
}
onUnmount = () => {
// clear cookies
}
componentWillUnmount() {
window.removeEventListener('beforeunload', this.onUnmount, false);
this.onUnmount();
}
beforeunload
may not work in some browsers and isn't reliable.
This is XY problem. This has been previously handled by cookie expiration, a cookie may be short-lived but renewed periodically when browser window is open.
Currently cookies can be considered outdated in general because there are localStorage
and sessionStorage
. Sensitive data like credentials can be stored in sessionStorage
. It is automatically cleared on browser exit.
Upvotes: 7