Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can i update a cookie without resetting its expiry date #82

Open
rayan-nativex opened this issue Apr 30, 2019 · 1 comment
Open

Comments

@rayan-nativex
Copy link

I want to be able to set an expiry date to the cookie and add some data to that cookie on certain events without resetting the expiry of it .. how can that be achieved using this library?

@rayan-nativex
Copy link
Author

rayan-nativex commented May 2, 2019

This is what I used in case someone is stuck at this point..
Please feel free to edit my solution .. or suggest other ones too..
And please support updating the cookie in this library as a request

// Helper function to set how many days to expire the cookie
       setExpiry = function(days){
            var minute = 60,
            second = 60,
            day=24,
            ms = days * day * minute * second,
            date = new Date();
            date.setTime(date.getTime()+(ms *1000));
            return { ms: ms, date: date.toUTCString()};
        }

// use this function to set a cookie or override it .. note that this will override the expiry date
        setCookie = function(name,data,expiry) {
            if(expiry){
                // resetting the cookie
                Cookie.setJSON(name, {data: data, expires: this.setExpiry(expiry).date}, { expires: this.setExpiry(expiry).ms});
                return;
            }
            // no expiry date
            Cookie.setJSON(name, data);
        }

// use this function to update a cookie keeping the same expiry date
        updateCookie = function(name, data){
            if(this.getCookie(name)){
                var getCookie = this.getCookie(name);
                var today = new Date();
                var expiryDate = new Date(this.getCookie(name).expires);
                var timeDiff = Math.abs(today.getTime() - expiryDate.getTime());
                daysLeft = Math.ceil(timeDiff / (1000 * 3600 * 24));
                this.setCookie(name, data, daysLeft);
                return;
            }
            console.error('Update Failed! Cookie {'+ name +'} doesnt exist.');
        }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant