In my ReactJS project, currently I am saving the cookie like cookie.save('token', received_token, { path: '/'} );
and retrieving it from the local storage like so: cookie.load('token');
.
So I was wondering, is a way to set expiration time when .save()
the token received, and once expired, automatically have it remove itself from the local storage?
Thank you and will accept the answer with vote up.
Just set the expires parameter to a past date: document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; You should define the cookie path to ensure that you delete the right cookie.
Or you might use mktime(). time()+60*60*24*30 will set the cookie to expire in 30 days. If not set, the cookie will expire at the end of the session (when the browser closes). The path on the server in which the cookie will be available on.
A temporary cookie expires when a web browser session ends – usually, this happens when the browser program is closed down. This is a session cookie. The cookie's data is not stored on your computer permanently. The data in a persistent cookie is stored on your computer for a specified time period.
You can pass maxAge
or expires
in options as 3rd parameter in cookie.save
function
Syntax:
reactCookie.save(name, val, [opt])
Example:
// maxAge Example
reactCookie.save("token", "token-value", {
maxAge: 3600 // Will expire after 1hr (value is in number of sec.)
});
// Expires Example
var tomorrow = new Date();
tomorrow.setDate(today.getDate()+1);
reactCookie.save("token", "token-value", {
expires: tomorrow // Will expire after 24hr from setting (value is in Date object)
});
Documentation: https://github.com/eXon/react-cookie#reactcookiesetrawcookiecookies
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