Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add listener for Reactjs cookies

I'm setting a React cookie in 1 component (Menu.js) and trying to listen for it in another component (Home.js)

Currently using universal-cookie: https://www.npmjs.com/package/universal-cookie and there is an addChangeListener function. However, I can't seem to get it working, this code snippet in Home.js simply doesn't trigger an update when I set the cookie in Menu.js.

const cookies = new Cookies();

cookies.addChangeListener(onCookieChange);

function onCookieChange() {
  console.log("Noticed cookie change!")
}

Tried binding onCookieChange like this according to other stackoverflow answers:

cookies.addChangeListener(this.onCookieChange.bind(this));

and got this error:

TypeError: Cannot read property 'onCookieChange' of undefined
like image 642
Joyce Sin Avatar asked Dec 02 '25 23:12

Joyce Sin


1 Answers

A little late here but here's how can you listen for cookie changed with a simple useEffect hook. When MyComponent is mounted it adds the listener, and when MyComponent is unmounted the listener is removed.

const cookies = new Cookies();

const MyComponent = () => {

  useEffect(() => {
    const cookieChangeListener = (name, value) => {
      console.log('The cookie ', name, ' changed to ', value)
    }

    cookies.addChangeListener(cookieChangeListener);

    return () => {
      cookies.removeChangeListener(cookieChangeListener);
    }
  },[]);
  
  ...
}
like image 162
Andrew Avatar answered Dec 04 '25 11:12

Andrew