skip to Main Content

I’m trying to have cookies set, and then subsequently loaded upon the next page. I currently add items to my "Cart" and upon checking logs and inspecting, they are not being logged to console, but then not actually being set. This is in javascript, server on node.

const shoppingCart = [];

//Convery array to JSON string and set as cookie
function saveCartToCookie() {
  const cartJSON = JSON.stringify(shoppingCart);
  console.log("Saving cart to cookie:", cartJSON);
  document.cookie = `shoppingCart=${cartJSON}; path=/`;
}

function loadCartFromCookie() {
  const cookieData = document.cookie.split(';').find(cookie => cookie.trim().startsWith('shoppingCart='));
  if (cookieData) {
    const cartJSON = cookieData.split('=')[1];
    console.log("Loading cart from cookie:", cartJSON);
    shoppingCart.length = 0; // Clear the current cart
    shoppingCart.push(...JSON.parse(cartJSON)); // Load cart from cookie
  }
}

Pulled into my html as such;

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-HwwvtgBNo3bZJJLYd8oVXjrBZt8cqVSpeBNS5n7C8IVInixGAoxmnlMuBnhbgrkm"
    crossorigin="anonymous"></script>
  <script src="../utils/cart.js"></script>

I have tried chrome, edge, as well as having it hosted on localhost and my github. Any idea where I’m going wrong would be much appreciated!

2

Answers


  1. Chosen as BEST ANSWER

    Turns out I was trying to save the cookie when working on my project through "//file" instead of localhost 3000/whatever. This was the source of the problem. File doesnt work with cookies!


  2. document.cookie = `shoppingCart=${cartJSON}; path=/`;

    In your code, I found a problem with symbols. You should be using single quotes instead of backquote. It should be something like this:

    document.cookie = 'shoppingCart=${cartJSON}; path=/';
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search