1

This is code in which i am setting the cookie

document.cookie = 'cookie_consent=true; expires=Fri, 31 Dec 9999 23:59:59 GMT Secure';

Below is my code for checking cookie.

useEffect(() => {
const cookieValue = (`; ${document?.cookie}`).split('; cookie_consent=').pop().split(';')[0];
if (!cookieValue) {
  console.log("Cookie not avaliable");
}
}, [document?.cookie]);

Cookie is getting expired after accepting within few days since i set cookie expiry as 31 dec 9999 etc.

Thank You in advance, Any help will appreciated.

Priyen Mehta
  • 1,096
  • 1
  • 5
  • 19

2 Answers2

0

My assumption would be immediately that 9999 is too great as a year.

See the following post: https://stackoverflow.com/questions/10328361/maximum-lifetime-of-javascript-cookie#:~:text=The%20max%20value%20is%202,on%20the%20UNIX%20timestamp%20value.

ThePigeon
  • 1
  • 2
0

As a side note, set useEffect with document.cookie as a dependence will not re-run when document.cookie change, it only accepts state dependencies

Also,

All the cookies expire as per the cookie specification. So, there is no block of code you can write in JavaScript to set up a cookie that never expires. It is just impossible and is a fact.

Solution: But you can set up a cookie that expires in JavaScript and pick some very large value as expiry date as specified below:

const expireDate = new Date(2147483647 * 1000).toUTCString();

document.cookie = `cookie_consent=true; expires=${expireDate} Secure`;
Mina
  • 14,386
  • 3
  • 13
  • 26
  • https://stackoverflow.com/a/68118690/19431815 - As per this answer useEffect will re-run on any data change. – Priyen Mehta Jul 13 '22 at 10:29
  • This question or answer doesn't mean that the `useEffect` can be updated if `normal variable` is updated, it means that `useEffect` can be updated with any `state` dependence even if it doesn't use inside the `useEffect`. – Mina Jul 13 '22 at 11:01
  • Anyway, if you have set up eslint in your code editor, you will get this warning message if you set `document.cookie` as dependence on `useEffect`. `React Hook useEffect has an unnecessary dependency: 'document.cookie'. Either exclude it or remove the dependency array. Outer scope values like 'document.cookie' aren't valid dependencies because mutating them doesn't re-render the component. (react-hooks/exhaustive-deps)` – Mina Jul 13 '22 at 11:03
  • 1
    Thank you , Got it. I will try your changes and let you know if anything occurs. – Priyen Mehta Jul 14 '22 at 07:06