angularjscookiessession-cookiescookiestoreangular-cookies

$cookieStore not saving the data for another iteration of a method


I have an application where i have checkboxes for each item(configurations) from an array(configurationsArray). What i want to implement is to add the configuration to the cookie store when checkbox is checked

Here is my code

    $scope.addProjectConfig = function(configuration, projectName) {
            var configs = $cookieStore.get('projectsToCompare');
            if(!configs) {
                $cookieStore.put('projectsToCompare', new Array());
                configs = $cookieStore.get('projectsToCompare');
            }

            if(configuration.addedToCompare) {
                var configObject = {projectName: projectName, configuration: configuration};
                configs.push(configObject);
                $cookieStore.put('projectsToCompare', configs);
            } 

            var configs1 = $cookieStore.get('projectsToCompare');
        };

If you see in the end i try to get the stuff i pushed in the cookieStore and it works fine.

However when another checkbox is checked and the method gets executed again, i see that the value returned in the beginning has an empty array. What am i doing wrong here? Any pointers are deeply appreciated.


Solution

  • One possible reason for the behavior you are observing is, your cookie size is more than the cookie size limit for your browser.

    Read more about cookie size limits here & here.

    Excerpts from the second link

    According to the RFC 2109, web cookies should not be limited by user agents. But the minimum capabilities of a browser or user agent should be at least 4096 bytes per cookie. This limit is applied to the name=value portion of the cookie only.

    This means that if you're writing a cookie and the cookie is less than 4096 bytes, then it will be supported by every browser and user agent that conforms to the RFC.

    Cookie Size limits for various browsers

    • Internet Explorer 8 allowed cookies up to 4095 bytes
    • Chrome 9 allowed cookies up to 4096 bytes
    • Opera 11 allowed cookies up to 4096 bytes
    • Firefox 3.6.3 allowed cookies up to 4097 bytes
    • Safari 5 allowed coookies up to 4097 bytes

    You can test your browser cookie size limit by going to this link and clicking

    Run Tests For Current Browser

    So if this is indeed the case then you need to reduce your cookie size. If you don't want to do that, and assuming you are developing for HTML5, there are other simple ways to tackle this.

    If you want to persist the data only for that session, use sessionStorage else use localStorage. Read more about sessionStorage and localStorage here