Daiaiai
Daiaiai

Reputation: 1089

Check my cookie

I am trying to set a cookie-value for somebody who visits my index-page with cookie.js like so:

<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>

<script> 
  var index_da = Cookies.get('sw_home_visit');

    if (index_da < 1) {
        Cookies.set('sw_home_visit', '1', {
            expires: 365
        });
        console.log("nicht da")
    } else {
        console.log("da")
    }
</script>

As I get printed "da" all the time in my console this can have several reasons I guess; is this then right or what do I need to correct?

Upvotes: 0

Views: 74

Answers (1)

Junior Dussouillez
Junior Dussouillez

Reputation: 2397

Cookies.get('sw_home_visit');

This line returns undefined because the cookie does not exist. undefined < 1 is always false. Change your code in something like :

Cookies.get('sw_home_visit') || 0;

If the cookie does not exist, the value will be 0 and the cookie will be created. Or change your if condition to handle undefined results.

Upvotes: 2

Related Questions