4

I'm using the library react-cookie (https://www.npmjs.com/package/react-cookie) and I want to delete the user cookies when the browser or tab is closed. I used ComponentWillUnmount in my Approuter, but that doesn't work when the browser is closed. Anyone know how to achieve this?

import React from 'react';
import {Router, Route, Switch} from 'react-router-dom';
import history from '../data/history';
import { withCookies, Cookies } from 'react-cookie';
import { instanceOf } from 'prop-types';


class AppRouter extends React.Component{

static propTypes = {
    cookies: instanceOf(Cookies).isRequired
};


constructor(props){
    super(props)
}

componentWillMount(){
    const {cookies} = this.props;
    cookies.remove('userInfo');
}

render(){
    return(
        <Router history={history}>
            <div>
                <Header/>
                <div className="main-container">
                    <Switch>
                        //routes
                    </Switch>
                    <Footer/>
                </div> 
            </div>
        </Router>
    );
}
}

export default withCookies(AppRouter);

The router does receive the cookies so why can't I remove it with componentWillUnmount? And how do I remove them?

djamaile
  • 695
  • 3
  • 12
  • 30

4 Answers4

2

When you create cookie. please set expires to 0. e.g

cookies.set('userInfo', name, { expires: 0 });

Then this cookie will be expired when browser closed.

Julian
  • 1,592
  • 1
  • 13
  • 33
  • This works when the browser is completely is shut down, but not when the tab is closed. Any tips for that? – djamaile Nov 26 '18 at 12:18
0

Old post but today I was needing this and did some search and found nothing, until I came up with an easy solution. Posting here hoping it will help someone.

You just need to add the following to your 'index.js':

const handleBeforeUnload = () => {
  Cookies.remove('userinfo');
};
window.addEventListener('beforeunload', handleBeforeUnload);
-1

Not really React specific but you can use this :

window.addEventListener("beforeunload", (ev) => 
{  
    ev.preventDefault();
    cookies.remove('userInfo');
});

Maybe call it on mount so you can have access your class instance.

Fawzi
  • 359
  • 2
  • 12
-1

This may help you...

componentDidMount(){
    window.addEventListener(
        "beforeunload",
        cookies.remove('userInfo')
    );
}
onejeet
  • 1,191
  • 6
  • 14