'Using localStorage in liquid

I'm building ann app for Shopify and faced an issue which I can't solve at the moment. Context: I have an array of products saved in a state.products in localStorage

state: {
   products: [ productId1, productId2, productId3]
}

If an Id of a product (which i store in product Shopify object https://shopify.dev/api/liquid/objects/product) is in the products array, then I want to render an icon, otherwise nothing is rendered

This trick doesn't work (I guess since liquid is working on a server side):

{% assign state = JSON.parse(localStorage.getItem('state')) %}
{% products = state.products %}
{% if products contains {{product.id}} %}
   <svg />
{% endif %}

So my question is, how can I assign an array which is stored in localStorage to a liquid variable?



Solution 1:[1]

Short answer: No, this is not possible

The first thing to remember when working with a Shopify site is that Liquid is a templating language, not a scripting language. When a visitor requests a page on your store, Shopify's servers interpret the Liquid commands to assemble a final document that is sent over the internet to the customer's browser without any templating marks in it - the final result is just a normal page of HTML, Javascript or CSS.

The server putting the page together has no knowledge of any given shopper's localStorage or anything else that exists in the Javascript context, so cannot use any of those values when constructing the page to send to the user.

What can we do instead?

You have everything you need to create/display the SVG using Javascript without needing to rely on Liquid to print the element!

Since you're storing an array of product IDs, you can do something like this on your product page:

<script>
  const currentProductId = {{ product.id | json }};
  const productArray = JSON.parse(localStorage.getItem('state'));

  if(productArray.includes(currentProductId)){
    // Code to create or display the SVG in question
  }
</script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dave B