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
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);
}
},[]);
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With