Cookie-Stored Setting Not Applying

I am making a setting in my WooCommerce website where the user can choose between a table view and a grid view of the products. I use cookies for this. The setting works sometimes when clicking on it; but when changing page, when there is pagination, it doesn’t always retain the selected view.

I set the cookie like this:

document.cookie = "Techsaker_se_vyval=Rutnätsvy";

And then, in my content-product.php file I check it like this:

// If products view not set to grid, show table view
if (($_COOKIE['Techsaker_se_vyval']) != 'Rutnätsvy') {

It seems the cookie value isn’t retained.

Additionally, it will sometimes also show the table view on one page of a product category, and then the grid view on a different page.

I have also observed that if I print the cookie value to the console with console.log, the value is often different from when I print it from the php with:

var_dump($_COOKIE['Techsaker_se_vyval']);

For example when I tested this, they showed conflicting values on page 1 of my shop startpage and the same values on page/2/. And I could only change the value successfully on page 2.

After further tests, I observed that the JavaScript and php sometimes do show the same value also on page 1, but even then, I couldn’t change the view on page 1. On clicking on an option, the JavaScript value in the console sometimes changes without changing the view printed, sometimes not even that. However; in a product category, as opposed to the shop startpage, I have seen that sometimes I can change the view on both page 1 and page 2.

It’s always the php value that determines what view is output. Why isn’t it always registering the same value as the JavaScript?

And changing the view always seems to work when it’s on page 2.

Does anyone know why this could be happening?

Thank you!