React Cookie + ReactJS: How to set expiration time for a cookie?

∥☆過路亽.° 提交于 2019-12-01 05:35:43

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/40229782/react-cookie-reactjs-how-to-set-expiration-time-for-a-cookie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!