Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-cookie unable to set expires or maxAge

I cannot seem to set the expiration for a cookie with react-cookie... here is my setup:

import { Cookies } from 'react-cookie'
const cookies = new Cookies()
import moment from 'moment'

The following attempts have failed:

cookies.set('cookieName', {key: value}, {path: '/', expires: new Date(Date.now()+2592000)})
cookies.set('cookieName', {key: value}, {path: '/', expires: moment().add(30, "days")})
cookies.set('cookieName', {key: value}, {path: '/', maxAge: 2592000})

Chrome continues to present:

Expires
When the browsing session ends
like image 985
JasonA Avatar asked Dec 17 '17 23:12

JasonA


3 Answers

It seems that Cookies from react-cookie has been moved to the universal-cookie package. So the following should work:

import Cookies from 'universal-cookie';

const cookies = new Cookies();
cookies.set('cookieName', {key: value}, {path: '/', expires: new Date(Date.now()+2592000)});
like image 143
kalpetros Avatar answered Oct 12 '22 02:10

kalpetros


Example with expire after one year

import Cookies from 'universal-cookie';

const cookies = new Cookies();
const current = new Date();
const nextYear = new Date();

nextYear.setFullYear(current.getFullYear() + 1);

cookies.set('cookieName', true, {
    path: '/',
    expires: nextYear,
});

Here you can see more on how to use Date.set https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear

like image 24
Stefan Lindberg Avatar answered Oct 12 '22 01:10

Stefan Lindberg


A little late, but if anyone out there is still having trouble with this. In universal-cookie try using the maxAge option instead of expires.

Here's a snippet of how I got mine to work.

cookies.set("theme", 0, {
    path: "/",
    maxAge: 1000000
});

Being honest you're better off using the normal cookie setting stuff. Info Here

You're gonna have to use document.cookie anyway to interact with your already set cookie right from loading anyways. Here's a snippet of my code for that. Along with the useState hook for reference.

Like shown in this doc, document.cookie shows you a list of all cookies output like this.

cookieOne=1; cookieTwo=poopy; cookieThree=etc

So, write something like this out. Substituting "theme" for your cookie name. This code will give you that value.

const docThemeCookie = document.cookie
  .split("; ")
  .find((row) => row.startsWith("theme"))
  .split("=")[1];

You'll get a string back no matter what, so if its a int or anything else convert appropriately. Here's my useState hook with my cookie needing to be an int.

const [theme, setTheme] = useState(parseInt(docThemeCookie, 10));

Hope that helps whoever is still stuck!

TLDR;

Use maxAge instead of expires.

Use document.cookie to check initial cookie value for state.

like image 2
Xyloid Avatar answered Oct 12 '22 01:10

Xyloid